@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)