Skip to content

api

api

DATA_ROOT: Path | None = Path(env_data_root) if env_data_root is not None else None module-attribute

LOGLEVEL: str = 'INFO' module-attribute

app = Flask(__name__) module-attribute

env_data_root = os.environ.get('QSL_DATA_ROOT', None) module-attribute

api_export()

Source code in src/qgis_server_light/exporter/api.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
@app.route(
    "/export",
    methods=["POST"],
)
def api_export():
    global DATA_ROOT, LOGLEVEL
    response_mime_type = "text/json"
    if DATA_ROOT is None:
        e = (
            "Something is wrong with the DATA_ROOT, it has the value None."
            "This means the api has started wrongly, we cant run the export."
        )
        app.logger.error(e)
        result = ExportResult(successful=False, content=e)
        return Response(JsonSerializer().render(result), mimetype=response_mime_type)
    body = request.get_json()
    app.logger.debug(f"Received a new task to export {type(body)} {body}")
    parser_config = ParserConfig(fail_on_unknown_properties=True)
    try:
        parameters = JsonParser(config=parser_config).from_string(body, ExportParameters)
    except Exception as e:
        app.logger.exception(e)
        result = ExportResult(successful=False, content=str(e))
        return Response(JsonSerializer().render(result), mimetype=response_mime_type)

    qualified_path = assemble_project_base_path(DATA_ROOT, parameters.project_path)
    if not qualified_path.exists():
        e = f"project_file: {parameters.project_path} DOES NOT EXISTS in dataroot"
        app.logger.info(e)
        result = ExportResult(successful=False, content=str(e))
        return Response(JsonSerializer().render(result), mimetype=response_mime_type)

    try:
        process = subprocess.run(
            [
                sys.executable,
                "-m",
                "qgis_server_light.exporter.cli",
                "export",
                "--project",
                str(qualified_path),
                "--unify_layer_names_by_group",
                str(parameters.unify_layer_names_by_group),
                "--output_format",
                parameters.output_format,
            ],
            text=True,
            check=True,
            capture_output=True,
        )
        result = ExportResult(successful=True, content=process.stdout)
        app.logger.debug(f"Successfully extracted information from QGIS Project {result}")
    except subprocess.CalledProcessError as e:
        if e.returncode == ExportFailure.EXIT_CODE:
            result = ExportResult(successful=False, content=e.stdout)
            app.logger.debug(f"Unsuccessful extraction with structured error: {result}")
        else:
            app.logger.exception(e.stderr)
            error_message = ExportMessage(
                level=ExportMessage.Level.ERROR,
                code=ExportMessage.Code.UNEXPECTED_ERROR,
                message=str(e),
            )
            result_content = ResultWithMessages(
                project=Project(name=parameters.project_path, version=""),
                exporter=Exporter(qgis_version=""),
                messages=[error_message],
            )
            if parameters.output_format.lower() == "xml":
                serializer = XmlSerializer()
            else:
                serializer = JsonSerializer()
            result = ExportResult(successful=False, content=serializer.render(result_content))
    return Response(JsonSerializer().render(result), mimetype=response_mime_type)

assemble_output_file_path(project_base_path: Path, output_format: str) -> Path

Source code in src/qgis_server_light/exporter/api.py
35
36
def assemble_output_file_path(project_base_path: Path, output_format: str) -> Path:
    return Path(str(project_base_path) + f".{output_format}")

assemble_project_base_path(data_path: Path, project_path: str) -> Path

Source code in src/qgis_server_light/exporter/api.py
31
32
def assemble_project_base_path(data_path: Path, project_path: str) -> Path:
    return Path(data_path, project_path)

main() -> None

Just the central cli entry command. Currently, we don't use it, but its here for future content.

Source code in src/qgis_server_light/exporter/api.py
115
116
117
118
119
120
121
122
@click.group
def main() -> None:
    """
    Just the central cli entry command. Currently, we don't use it, but its here
    for future content.

    """
    pass

start(data_root, host: str = '127.0.0.1', port: int = 5000, log_level: str = 'info')

Source code in src/qgis_server_light/exporter/api.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
@click.option(
    "--data-root",
    help="The host address the service will be started on.",
)
@click.option(
    "--host",
    type=str,
    default="127.0.0.1",
    help="The host address the service will be started on.",
)
@click.option(
    "--port",
    type=int,
    default=5000,
    help="The port the service will be exposed to.",
)
@click.option(
    "--log-level",
    type=str,
    default="info",
    help="log level (debug, info, warning or error)",
)
@main.command(
    "start",
    context_settings={"max_content_width": 120},
    help="""
    Starts the exporter API. be sure to set the data_root to an accessible directory!
    """,
)
def start(
    data_root,
    host: str = "127.0.0.1",
    port: int = 5000,
    log_level: str = "info",
):
    global DATA_ROOT, LOGLEVEL
    root_path = Path(data_root)
    if root_path.exists() and root_path.is_dir():
        # we reset root path to the passed variable value and ignore ENV!
        DATA_ROOT = root_path
        LOGLEVEL = log_level.upper()
        app.run(
            host=host,
            debug=log_level.upper() in ["DEBUG"],
            threaded=False,
            port=port,
        )
    else:
        raise RuntimeError(f"Mandatory 'data_root' => {data_root} does not exist or is not a dir.")