Skip to content

Exporter

api

allowed_extensions = ('qgz', 'qgs') module-attribute

allowed_output_formats = ('json', 'xml') module-attribute

app = Flask(__name__) module-attribute

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

qgs = QgsApplication([], False) module-attribute

api_export()

Source code in src/qgis_server_light/exporter/api.py
32
33
34
35
36
37
38
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
@app.route("/export", methods=["POST"])
def api_export():
    logging.getLogger().setLevel(logging.DEBUG)
    data_path = os.environ.get("QSL_DATA_ROOT")
    body = request.get_json()
    parser_config = ParserConfig(fail_on_unknown_properties=True)
    parameters: ExportParameters = DictDecoder(config=parser_config).decode(
        body, ExportParameters
    )
    serializer_config = SerializerConfig(indent="  ")

    # project file
    project_file = ""
    for extension in allowed_extensions:
        project_file = path.join(
            data_path, parameters.mandant, ".".join([parameters.project, extension])
        )
        print(f"testing project_file: {project_file}")
        if path.exists(project_file):
            print(f"project_file: {project_file} EXISTS")
            break
    if not path.exists(project_file):
        raise NotImplementedError(
            f"Project {parameters.project} from mandant {parameters.mandant} not found."
        )
    print(f"project_file: {project_file}")

    # output format
    if not parameters.output_format.lower() in allowed_output_formats:
        raise NotImplementedError(
            f'Allowed output formats are: {"|".join(allowed_output_formats)} not => {parameters.output_format}'
        )
    output_format = parameters.output_format.lower()

    # extract
    config = extract(
        path_to_project=project_file,
        unify_layer_names_by_group=bool(parameters.unify_layer_names_by_group),
    )
    result = ExportResult(successful=False)

    content = None
    if output_format == "json":
        content = JsonSerializer(config=serializer_config).render(config)
    elif output_format == "xml":
        content = XmlSerializer(config=serializer_config).render(config)
    else:
        return Response(JsonSerializer().render(result), mimetype="text/json")
    if content:
        with open(
            path.join(
                data_path,
                parameters.mandant,
                ".".join([parameters.project, output_format]),
            ),
            mode="w+",
        ) as f:
            f.write(content)
    result.successful = True
    return Response(JsonSerializer().render(result), mimetype="text/json")

cli

allowed_extensions = ('qgz', 'qgs') module-attribute

allowed_output_formats = ('json', 'xml') module-attribute

qgs = QgsApplication([], False) module-attribute

cli()

Source code in src/qgis_server_light/exporter/cli.py
20
21
22
@click.group
def cli():
    pass

export(project, unify_layer_names_by_group=False, output_format=None)

Source code in src/qgis_server_light/exporter/cli.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@click.option("--project")
@click.option("--unify_layer_names_by_group")
@click.option("--output_format")
@cli.command(
    "export",
    help=f"Export a QGIS project ({f'|'.join(allowed_extensions)}) (1st argument) file to json format",
)
def export(
    project: str,
    unify_layer_names_by_group: bool = False,
    output_format: str | None = None,
) -> None:
    serializer_config = SerializerConfig(indent="  ")
    if output_format is None:
        output_format = "json"
    if not project.lower().endswith(allowed_extensions):
        raise NotImplementedError(
            f'Allowed qgis project file extensions are: {"|".join(allowed_extensions)} not => {project}'
        )
    if not output_format.lower() in allowed_output_formats:
        raise NotImplementedError(
            f'Allowed output formats are: {"|".join(allowed_output_formats)} not => {output_format}'
        )
    if os.path.isfile(project):
        config = extract(
            path_to_project=project,
            unify_layer_names_by_group=bool(unify_layer_names_by_group),
        )
        if output_format == "json":
            click.echo(JsonSerializer(config=serializer_config).render(config))
        elif output_format == "xml":
            click.echo(XmlSerializer(config=serializer_config).render(config))

    else:
        raise AttributeError("Project file does not exist")

extract

create_style_list(qgs_layer)

Source code in src/qgis_server_light/exporter/extract.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
def create_style_list(qgs_layer: QgsMapLayer) -> List[Style]:
    style_names = qgs_layer.styleManager().styles()
    style_list = []
    for style_name in style_names:
        style_doc = QDomDocument()
        qgs_layer.styleManager().setCurrentStyle(style_name)
        qgs_layer.exportNamedStyle(style_doc)
        style_list.append(
            Style(
                name=style_name,
                definition=urlsafe_b64encode(
                    zlib.compress(style_doc.toByteArray())
                ).decode(),
            )
        )
    return style_list

create_unified_short_name(name, path)

Source code in src/qgis_server_light/exporter/extract.py
224
225
226
def create_unified_short_name(name: str, path: list[str]):
    short_name_part = path + [name]
    return ".".join(short_name_part)

decide_sslmode(ssl_mode)

Mapper to map ssl modes from QGIS to plain postgres.

Parameters:

Name Type Description Default
ssl_mode int

The ssl mode of the datasource.

required

Returns:

Type Description
str

The string representation of the ssl mode as it is used by postgres connections.

Raises: LookupError: If the given ssl mode is not supported.

Source code in src/qgis_server_light/exporter/extract.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def decide_sslmode(ssl_mode: int) -> str:
    """
    Mapper to map ssl modes from QGIS to plain postgres.

    Args:
        ssl_mode: The ssl mode of the datasource.

    Returns:
        The string representation of the ssl mode as it is used by postgres connections.
    Raises:
        LookupError: If the given ssl mode is not supported.
    """
    if ssl_mode == QgsDataSourceUri.SslDisable:
        return "disable"
    elif ssl_mode == QgsDataSourceUri.SslAllow:
        return "allow"
    elif ssl_mode == QgsDataSourceUri.SslPrefer:
        return "prefer"
    elif ssl_mode == QgsDataSourceUri.SslRequire:
        return "require"
    elif ssl_mode == QgsDataSourceUri.SslVerifyCa:
        return "verify-ca"
    elif ssl_mode == QgsDataSourceUri.SslVerifyFull:
        return "verify-full"
    else:
        raise LookupError(f"Unknown ssl mode {ssl_mode}")

extract(path_to_project, unify_layer_names_by_group=False)

Extract the styles and configuration of the given Qgis project to the given output directory.

Source code in src/qgis_server_light/exporter/extract.py
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
def extract(path_to_project: str, unify_layer_names_by_group=False) -> Config:
    """
    Extract the styles and configuration of the given Qgis project
    to the given output directory.
    """
    project, root = get_project_root(path_to_project)
    version, assembled_name = prepare_project_name(project)
    tree = Tree()
    datasets = Datasets()
    config = Config(
        project=Project(name=assembled_name, version=version),
        meta_data=extract_metadata(project),
        tree=tree,
        datasets=datasets,
    )
    extract_entities(project, root, tree, datasets, [], unify_layer_names_by_group)
    return config

extract_entities(project, entity, tree, datasets, path, unify_layer_names_by_group=False, types_from_editor_widget=False)

Source code in src/qgis_server_light/exporter/extract.py
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
def extract_entities(
    project: QgsProject,
    entity: Union[QgsLayerTree, QgsLayerTreeGroup, QgsLayerTreeLayer],
    tree: Tree,
    datasets: Datasets,
    path: list[str],
    unify_layer_names_by_group=False,
    types_from_editor_widget: bool = False,
):
    if isinstance(entity, QgsLayerTreeLayer):
        extract_save_layer(
            project,
            entity,
            tree,
            datasets,
            path,
            unify_layer_names_by_group,
            types_from_editor_widget,
        )

    # If the entity has an attribute `children`, assume it's a group
    elif isinstance(entity, QgsLayerTreeGroup) or isinstance(entity, QgsLayerTree):
        short_name = get_group_short_name(entity)
        if short_name != "":
            # '' is the root of the tree, we dont want it to be part of the path
            path = path + [short_name]
        extract_group(
            entity,
            tree,
            datasets,
            path,
            unify_layer_names_by_group,
            types_from_editor_widget,
        )
        for child in entity.children():
            extract_entities(
                project,
                child,
                tree,
                datasets,
                path,
                unify_layer_names_by_group,
                types_from_editor_widget,
            )

extract_fields(layer, types_from_editor_widget=False)

Source code in src/qgis_server_light/exporter/extract.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def extract_fields(
    layer: QgsVectorLayer, types_from_editor_widget: bool = False
) -> List[Field]:
    fields = []
    pk_indexes = layer.dataProvider().pkAttributeIndexes()
    for field_index, field in enumerate(layer.fields()):
        attribute_type_xml = obtain_simple_types_xml(field)
        if types_from_editor_widget:
            editor_widget_type = obtain_simple_types_from_editor_widget(field)
            if editor_widget_type:
                attribute_type_xml = editor_widget_type
        attribute_type_json, attribute_type_json_format = obtain_simple_types_json(
            field
        )
        fields.append(
            Field(
                is_primary_key=(field_index in pk_indexes),
                name=field.name(),
                type=field.typeName(),
                type_wfs=attribute_type_xml,
                type_oapif=attribute_type_json,
                type_oapif_format=attribute_type_json_format,
                alias=field.alias() or field.name().title(),
                comment=field.comment(),
                nullable=(field_index not in pk_indexes) and obtain_nullable(field),
                length=provide_field_length(field),
                precision=provide_field_precision(field),
            )
        )
    return fields

extract_group(group, tree, datasets, path, unify_layer_names_by_group=False, types_from_editor_widget=False)

Collects data pertaining to a QGIS layer tree group.

Source code in src/qgis_server_light/exporter/extract.py
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
def extract_group(
    group: QgsLayerTreeGroup,
    tree: Tree,
    datasets: Datasets,
    path: list[str],
    unify_layer_names_by_group=False,
    types_from_editor_widget: bool = False,
):
    """Collects data pertaining to a QGIS layer tree group."""
    children = []
    for child in group.children():
        if isinstance(child, QgsLayerTreeGroup):
            children.append(get_group_short_name(child))
        else:
            if unify_layer_names_by_group:
                children.append(
                    create_unified_short_name(get_layer_short_name(child), path)
                )
            else:
                children.append(get_layer_short_name(child))
    tree.members.append(TreeGroup(name=get_group_short_name(group), children=children))
    datasets.group.append(
        Group(
            name=get_group_short_name(group),
            title=get_group_title(group),
        )
    )

extract_metadata(project)

Construct a JSON object from the given layers and metadata

Source code in src/qgis_server_light/exporter/extract.py
655
656
657
658
659
660
661
662
663
664
665
666
667
def extract_metadata(project) -> MetaData:
    """Construct a JSON object from the given layers and metadata"""
    _meta = project.metadata()
    wms_entries = get_project_server_entries(project, "wms")
    service = Service(**dict(sorted({**wms_entries}.items())))
    return MetaData(
        service=service,
        author=_meta.author(),
        categories=_meta.categories(),
        creationDateTime=_meta.creationDateTime().toPyDateTime().isoformat(),
        language=_meta.language(),
        links=_meta.links(),
    )

extract_save_layer(project, child, tree, datasets, path, unify_layer_names_by_group=False, types_from_editor_widget=False)

Save the given layer to the output path.

Source code in src/qgis_server_light/exporter/extract.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
def extract_save_layer(
    project: QgsProject,
    child: QgsLayerTreeLayer,
    tree: Tree,
    datasets: Datasets,
    path: list[str],
    unify_layer_names_by_group: bool = False,
    types_from_editor_widget: bool = False,
):
    """Save the given layer to the output path."""
    layer = child.layer()

    QDomDocument()

    layer_type = get_layer_type(layer)
    decoded = QgsProviderRegistry.instance().decodeUri(
        layer.providerType(), layer.dataProvider().dataSourceUri()
    )
    logging.debug(f"Layer source: {decoded}")
    for key in decoded:
        if str(decoded[key]) == "None":
            decoded[key] = None
        elif str(decoded[key]) == "NULL":
            decoded[key] = None
        else:
            decoded[key] = str(decoded[key])
        if key == "path":
            decoded[key] = decoded[key].replace(f'{project.readPath("./")}/', "")
    short_name = get_layer_short_name(child)
    if unify_layer_names_by_group:
        short_name = create_unified_short_name(short_name, path)
    layer_crs = layer.dataProvider().crs()
    crs = Crs(
        postgis_srid=layer_crs.postgisSrid(),
        auth_id=layer_crs.authid(),
        ogc_uri=layer_crs.toOgcUri(),
        ogc_urn=layer_crs.toOgcUrn(),
    )

    extent_wgs_84 = extent_in_wgs84(project, layer)
    bbox_wgs84 = BBox(
        x_min=extent_wgs_84[0],
        x_max=extent_wgs_84[2],
        y_min=extent_wgs_84[1],
        y_max=extent_wgs_84[3],
    )
    extent = layer.extent()
    bbox = BBox.from_list(
        [
            extent.xMinimum(),
            extent.yMinimum(),
            0.0,
            extent.xMaximum(),
            extent.yMaximum(),
            0.0,
        ]
    )
    if layer_type == "vector":
        source_path = layer.source()
        if layer.providerType().lower() == "ogr":
            source = DataSource(
                ogr=OgrSource(
                    path=decoded["path"],
                    layer_name=decoded["layerName"],
                    layer_id=decoded["layerId"],
                )
            )
        elif layer.providerType().lower() == "postgres":
            config = decoded
            if decoded.get("service"):
                service_config = pgserviceparser.service_config(decoded["service"])
                # merging pg_service content with config of qgis project (qgis project config overwrites
                # pg_service configs
                config = service_config | decoded
            if config.get("username"):
                username = config["username"]
            elif config.get("user"):
                username = config["user"]
            else:
                raise LookupError(
                    f"Configuration does not contain any info about the db user name {config}"
                )
            source = DataSource(
                postgres=PostgresSource(
                    dbname=config["dbname"],
                    # there is no type if it is a non geometric layer
                    geometry_column=config.get("geometrycolumn"),
                    host=config["host"],
                    key=config["key"],
                    password=config["password"],
                    port=config["port"],
                    schema=config["schema"],
                    srid=config.get("srid"),
                    table=config["table"],
                    # there is no type if it is a non geometric layer
                    type=config.get("type"),
                    username=username,
                    sslmode=decide_sslmode(int(config.get("sslmode", 0))),
                )
            )
            if decoded.get("service"):
                del config["service"]
            source_path = QgsProviderRegistry.instance().encodeUri(
                layer.providerType(), config
            )
            password = config["password"]
            source_path = source_path + f" user='{username}' password='{password}'"

        elif layer.providerType().lower() == "wfs":
            # TODO: Correctly implement source!
            source = WfsSource()
        else:
            logging.error(
                f"Unknown provider type {layer.providerType().lower()} for layer {layer.title() or layer.name()}"
            )
            return
        fields = extract_fields(layer, types_from_editor_widget)
        datasets.vector.append(
            Vector(
                path=source_path.replace(f'{project.readPath("./")}/', ""),
                name=short_name,
                title=layer.title() or layer.name(),
                styles=create_style_list(layer),
                driver=layer.providerType(),
                bbox_wgs84=bbox_wgs84,
                fields=fields,
                source=source,
                id=layer.id(),
                crs=crs,
                bbox=bbox,
                minimum_scale=layer.minimumScale(),
                maximum_scale=layer.maximumScale(),
                geometry_type_simple=layer.geometryType().name,
                geometry_type_wkb=layer.wkbType().name,
            )
        )
    elif layer_type == "raster":
        if layer.providerType() == "gdal":
            source = DataSource(
                gdal=GdalSource(path=decoded["path"], layer_name=decoded["layerName"])
            )
        elif layer.providerType() == "wms":
            if "tileMatrixSet" in decoded:
                source = DataSource(
                    wmts=WmtsSource(
                        contextual_wms_legend=decoded.get("contextualWMSLegend"),
                        crs=decoded["crs"],
                        dpi_mode=decoded.get("dpiMode"),
                        feature_count=decoded.get("featureCount"),
                        format=decoded["format"],
                        layers=decoded["layers"],
                        styles=decoded["styles"],
                        tile_dimensions=decoded.get("tileDimensions"),
                        tile_matrix_set=decoded["tileMatrixSet"],
                        tile_pixel_ratio=decoded.get("tilePixelRatio"),
                        url=decoded["url"],
                    )
                )
            else:
                if decoded.get("type") == "xyz":

                    source = DataSource(
                        xyz=XYZSource(
                            url=decoded["url"],
                            zmin=decoded.get("zmin") or 0,
                            zmax=decoded.get("zmax") or 14,
                        )
                    )
                else:
                    source = DataSource(
                        wms=WmsSource(
                            contextual_wms_legend=decoded.get("contextualWMSLegend"),
                            crs=decoded["crs"],
                            dpi_mode=decoded.get("dpiMode"),
                            feature_count=decoded.get("featureCount"),
                            format=decoded["format"],
                            layers=decoded["layers"],
                            url=decoded["url"],
                        )
                    )
        else:
            raise NotImplementedError(
                f"Unknown provider type: {layer.providerType().lower()}"
            )
        if source is not None:
            datasets.raster.append(
                Raster(
                    path=layer.source().replace(f'{project.readPath("./")}/', ""),
                    name=short_name,
                    title=layer.title() or layer.name(),
                    styles=create_style_list(layer),
                    driver=layer.providerType(),
                    bbox_wgs84=bbox_wgs84,
                    source=source,
                    id=layer.id(),
                    crs=crs,
                    bbox=bbox,
                    minimum_scale=layer.minimumScale(),
                    maximum_scale=layer.maximumScale(),
                )
            )
    elif layer_type == "custom":
        if layer.providerType().lower() in ["xyzvectortiles", "mbtilesvectortiles"]:
            source = DataSource(
                vector_tile=VectorTileSource(
                    styleUrl=decoded.get("styleUrl"),
                    url=decoded.get("url") or decoded.get("path"),
                    zmax=decoded.get("zmax") or 14,
                    zmin=decoded.get("zmin") or 0,
                    type=decoded["type"],
                )
            )
        else:
            raise NotImplementedError(
                f"Unknown provider type: {layer.providerType().lower()}"
            )
            # TODO: make this more configurable
        datasets.custom.append(
            Custom(
                path=layer.source().replace(f'{project.readPath("./")}/', ""),
                name=short_name,
                title=layer.title() or layer.name(),
                styles=create_style_list(layer),
                driver=layer.providerType(),
                bbox_wgs84=bbox_wgs84,
                source=source,
                id=layer.id(),
                crs=crs,
                bbox=bbox,
                minimum_scale=layer.minimumScale(),
                maximum_scale=layer.maximumScale(),
            )
        )
    else:
        raise NotImplementedError(f'Unknown layer_type "{layer_type}"')

get_group_short_name(group)

Source code in src/qgis_server_light/exporter/extract.py
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def get_group_short_name(group: QgsLayerTreeGroup) -> str:
    if group.customProperty("wmsShortName"):
        return group.customProperty("wmsShortName")
    elif hasattr(group, "groupLayer"):
        # since QGIS 3.38
        if group.groupLayer():
            if group.groupLayer().serverProperties():
                if group.groupLayer().serverProperties().shortName():
                    return group.groupLayer().serverProperties().shortName()
    short_name = sanitize_name(group.name(), lower=True)
    if short_name == "_":
        # this is the tree root, we return empty string here
        return ""
    return short_name

get_group_title(group)

Source code in src/qgis_server_light/exporter/extract.py
559
560
561
562
563
564
565
566
567
568
def get_group_title(group: QgsLayerTreeGroup) -> str:
    if group.customProperty("wmsTitle"):
        return group.customProperty("wmsTitle")
    elif hasattr(group, "groupLayer"):
        # since QGIS 3.38
        if group.groupLayer():
            if group.groupLayer().serverProperties():
                if group.groupLayer().serverProperties().title():
                    return group.groupLayer().serverProperties().title()
    return group.name()

get_layer_short_name(layer)

Source code in src/qgis_server_light/exporter/extract.py
571
572
573
574
575
576
577
def get_layer_short_name(layer: QgsLayerTreeLayer) -> str:
    if layer.layer().shortName():
        return layer.layer().shortName()
    elif hasattr(layer.layer(), "serverProperties"):
        if layer.layer().serverProperties().shortName():
            return layer.layer().serverProperties().shortName()
    return layer.layer().id()

get_project_root(path_to_project)

Returns a Tuple .

Source code in src/qgis_server_light/exporter/extract.py
677
678
679
680
681
def get_project_root(path_to_project) -> Tuple[QgsProject, QgsLayerTree]:
    """Returns a Tuple <Project, LayerTreeRoot>."""
    project = QgsProject.instance()
    project.read(path_to_project)
    return project, project.layerTreeRoot()

obtain_nullable(field)

Source code in src/qgis_server_light/exporter/extract.py
167
168
169
170
171
172
173
def obtain_nullable(field: QgsField):
    if not (
        field.constraints().constraints()
        == QgsFieldConstraints.Constraint.ConstraintNotNull
    ):
        return True
    return False

obtain_simple_types_from_editor_widget(field)

We simply mimikri QGIS Server here

TODO: This could be improved alot! Maybe we can also backport that to QGIS core some day?

Parameters:

Name Type Description Default
field QgsField

The field of an QgsVectorLayer.

required

Returns:

Type Description
str | None

Unified type name regarding

str | None
Source code in src/qgis_server_light/exporter/extract.py
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
def obtain_simple_types_from_editor_widget(field: QgsField) -> str | None:
    """
    We simply mimikri [QGIS Server here](https://github.com/qgis/QGIS/blob/de98779ebb117547364ec4cff433f062374e84a3/src/server/services/wfs/qgswfsdescribefeaturetype.cpp#L153-L192)

    TODO: This could be improved alot! Maybe we can also backport that to QGIS core some day?

    Args:
        field: The field of an `QgsVectorLayer`.

    Returns:
        Unified type name regarding
        [XSD spec](https://www.w3.org/TR/xmlschema11-2/#built-in-primitive-datatypes)
    """
    attribute_type = field.type()
    setup = field.editorWidgetSetup()
    config = setup.config()
    if setup.type() == "DateTime":
        field_format = config.get(
            "field_format", QgsDateTimeFieldFormatter.defaultFormat(attribute_type)
        )
        if field_format == QgsDateTimeFieldFormatter.TIME_FORMAT:
            return "time"
        elif field_format == QgsDateTimeFieldFormatter.DATE_FORMAT:
            return "date"
        elif field_format == QgsDateTimeFieldFormatter.DATETIME_FORMAT:
            return "dateTime"
        elif field_format == QgsDateTimeFieldFormatter.QT_ISO_FORMAT:
            return "dateTime"
    elif setup.type() == "Range":
        if config.get("Precision"):
            config_precision = int(config["Precision"])
            if config_precision != field.precision():
                if config_precision == 0:
                    return "integer"
                else:
                    return "decimal"

obtain_simple_types_json(field)

Parameters:

Name Type Description Default
field QgsField

The field of an QgsVectorLayer.

required

Returns:

Name Type Description
Tuple[str, str] | Tuple[str, None]

Unified type name regarding

Tuple[str, str] | Tuple[str, None]
IMPORTANT Tuple[str, str] | Tuple[str, None]

If type is not matched within the function it will be string always!

Source code in src/qgis_server_light/exporter/extract.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def obtain_simple_types_json(field: QgsField) -> Tuple[str, str] | Tuple[str, None]:
    """

    Args:
        field: The field of an `QgsVectorLayer`.

    Returns:
        Unified type name regarding
        [XSD spec](https://www.w3.org/TR/xmlschema11-2/#built-in-primitive-datatypes)
        IMPORTANT: If type is not matched within the function it will be `string` always!
    """
    attribute_type = field.type()
    if attribute_type == QMetaType.Type.Int:
        return "integer", None
    elif attribute_type == QMetaType.Type.UInt:
        return "integer", "uint32"
    elif attribute_type == QMetaType.Type.LongLong:
        return "integer", "int64"
    elif attribute_type == QMetaType.Type.ULongLong:
        return "integer", "uint64"
    elif attribute_type == QMetaType.Type.Double:
        return "number", "double"
    elif attribute_type == QMetaType.Type.Float:
        return "number", "float"
    elif attribute_type == QMetaType.Type.Bool:
        return "boolean", None
    elif attribute_type == QMetaType.Type.QDate:
        return "string", "date"
    elif attribute_type == QMetaType.Type.QTime:
        return "string", "time"
    elif attribute_type == QMetaType.Type.QDateTime:
        return "string", "date-time"
    else:
        return "string", None

obtain_simple_types_xml(field)

Parameters:

Name Type Description Default
field QgsField

The field of an QgsVectorLayer.

required

Returns:

Name Type Description
str

Unified type name regarding

str
IMPORTANT str

If type is not matched within the function it will be string always!

Source code in src/qgis_server_light/exporter/extract.py
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
def obtain_simple_types_xml(field: QgsField) -> str:
    """

    Args:
        field: The field of an `QgsVectorLayer`.

    Returns:
        Unified type name regarding
        [XSD spec](https://www.w3.org/TR/xmlschema11-2/#built-in-primitive-datatypes)
        IMPORTANT: If type is not matched within the function it will be `string` always!
    """
    attribute_type = field.type()
    if attribute_type == QMetaType.Type.Int:
        return "int"
    elif attribute_type == QMetaType.Type.UInt:
        return "unsignedInt"
    elif attribute_type == QMetaType.Type.LongLong:
        return "long"
    elif attribute_type == QMetaType.Type.ULongLong:
        return "unsignedLong"
    elif attribute_type == QMetaType.Type.Double:
        if field.length() > 0 and field.precision() == 0:
            return "integer"
        else:
            return "decimal"
    elif attribute_type == QMetaType.Type.Bool:
        return "boolean"
    elif attribute_type == QMetaType.Type.QDate:
        return "date"
    elif attribute_type == QMetaType.Type.QTime:
        return "time"
    elif attribute_type == QMetaType.Type.QDateTime:
        return "dateTime"
    else:
        return "string"

prepare_project_name(project)

Source code in src/qgis_server_light/exporter/extract.py
684
685
686
687
688
689
690
691
692
def prepare_project_name(project: QgsProject) -> tuple[str, str]:
    # TODO: Find a good approach to recognize different "versions" of a project.
    name = project.baseName()
    parts = name.split(".")
    version = parts.pop(0)
    assembled_name = ".".join(parts)
    if assembled_name == "":
        assembled_name = project.title()
    return version, assembled_name

provide_field_length(field)

Source code in src/qgis_server_light/exporter/extract.py
176
177
178
179
180
181
def provide_field_length(field: QgsField) -> int | None:
    length = field.length()
    if length > 0:
        return length
    else:
        return None

provide_field_precision(field)

Source code in src/qgis_server_light/exporter/extract.py
184
185
186
187
188
189
def provide_field_precision(field: QgsField) -> int | None:
    precision = field.precision()
    if precision > 0:
        return precision
    else:
        return None

sanitize_name(raw, lower=False)

Wandelt einen beliebigen String in einen WMS/WFS‑ und URL‑Pfad‑ kompatiblen Layer‑Kurznamen um.

Schritte: 1. Unicode‑NFD → ASCII‑Transliteration (entfernt Umlaute/Diakritika). 2. Alle Zeichen, die NICHT [A‑Za‑z0‑9_.‑] sind, durch '' ersetzen. 3. Mehrere Unterstriche auf einen reduzieren. 4. Führende/abschließende '', '.', '-' entfernen. 5. Falls der Name leer ist ODER nicht mit Buchstabe bzw. '' beginnt, vorne '' voranstellen. 6. Optional alles in Kleinbuchstaben konvertieren (lower=True).

Source code in src/qgis_server_light/exporter/extract.py
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
def sanitize_name(raw: str, lower: bool = False) -> str:
    """
    Wandelt einen beliebigen String in einen WMS/WFS‑ und URL‑Pfad‑
    kompatiblen Layer‑Kurznamen um.

    Schritte:
    1. Unicode‑NFD → ASCII‑Transliteration (entfernt Umlaute/Diakritika).
    2. Alle Zeichen, die NICHT [A‑Za‑z0‑9_.‑] sind, durch '_' ersetzen.
    3. Mehrere Unterstriche auf einen reduzieren.
    4. Führende/abschließende '_', '.', '-' entfernen.
    5. Falls der Name leer ist ODER nicht mit Buchstabe bzw. '_' beginnt,
       vorne '_' voranstellen.
    6. Optional alles in Kleinbuchstaben konvertieren (lower=True).
    """
    # 1. cleaning to ASCII
    ascii_str = unicodedata.normalize("NFKD", raw).encode("ascii", "ignore").decode()
    # 2. not allowed → '_'
    ascii_str = re.sub(r"[^A-Za-z0-9_.-]+", "_", ascii_str)
    # 3. remove multiple '_'
    ascii_str = re.sub(r"_+", "_", ascii_str)
    # 4. remove trailing chars
    ascii_str = ascii_str.strip("._-")
    # 5. ensure first char is correct (mainly xml stuff and URL)
    if not ascii_str or not re.match(r"[A-Za-z_]", ascii_str[0]):
        ascii_str = "_" + ascii_str
    # 6. Optional lowercase
    if lower:
        ascii_str = ascii_str.lower()
    return ascii_str

save_to_disk(path_to_output_dir, built)

Source code in src/qgis_server_light/exporter/extract.py
670
671
672
673
674
def save_to_disk(path_to_output_dir, built):
    path_to_config_json = path.join(path_to_output_dir, "config.json")

    with open(path_to_config_json, "w") as fh:
        json.dump(built, fh, indent=2)

funcs

compose(*fs)

Returns the left-to-right composition of any Iterable of functions. Ex: compose(f, g, h)(args, kwargs) == h(g(f(args, **kwargs)))

Source code in src/qgis_server_light/exporter/funcs.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def compose(*fs):
    """
    Returns the left-to-right composition of any Iterable of functions.
    Ex: compose(f, g, h)(*args, **kwargs) == h(g(f(*args, **kwargs)))
    """

    def reducer(out, f):
        if isinstance(out, tuple):
            args, kwargs = out
            if isinstance(args, tuple) and isinstance(kwargs, dict):
                return f(*args, **kwargs)

        return f(out)

    def capture_args(*args, **kwargs):
        return reduce(reducer, fs, (args, kwargs))

    return capture_args

extent_in_wgs84(project, layer)

Reprojects the layer's extent using a custom projection. Returns the coordinates as List of floats.

Source code in src/qgis_server_light/exporter/funcs.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def extent_in_wgs84(project, layer) -> List:
    """
    Reprojects the layer's extent using a custom projection.
    Returns the coordinates as List of floats.
    """
    tr = make_wgs84_geom_transform(project, layer)
    rect = layer.extent()
    reprojected_rect = tr.transform(rect)
    return [
        reprojected_rect.xMinimum(),
        reprojected_rect.yMinimum(),
        reprojected_rect.xMaximum(),
        reprojected_rect.yMaximum(),
    ]

get_layer_type(layer)

Gets the type of the given Qgis layer as a string if the type is supported.

Source code in src/qgis_server_light/exporter/funcs.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def get_layer_type(layer: QgsVectorLayer | QgsRasterLayer) -> str:
    """Gets the type of the given Qgis layer as a string if the type is supported."""
    if isinstance(layer, QgsRasterLayer):
        return "raster"
    elif isinstance(layer, QgsVectorLayer):
        return "vector"
    elif (
        isinstance(layer, QgsVectorTileLayer)
        or isinstance(layer, QgsTiledSceneLayer)
        or isinstance(layer, QgsPointCloudLayer)
        or isinstance(layer, QgsMeshLayer)
    ):
        return "custom"
    else:
        raise TypeError(f"Not implemented: {layer.type()}")

get_project_server_entries(project, scope_or_scopes)

Gets values from the fields displayed in QGIS under Project > Properties > Server. Returns a Dictionary holding all pairs of found at the corresponding scopes. Example: given scope_or_scope = "wms" (or: ["wms"]) returns { : , : ... } For now the implementation supports only WMS fields but can be easily expanded by adding to the Dictionary below.

Source code in src/qgis_server_light/exporter/funcs.py
 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def get_project_server_entries(project, scope_or_scopes: Union[str, List]) -> Dict:
    """
    Gets values from the fields displayed in QGIS under Project > Properties > Server.
    Returns a Dictionary holding all pairs of <key, value> found at the corresponding scopes.
    Example:
        given   scope_or_scope = "wms" (or: ["wms"])
        returns { <wms_key1>: <wms_key1_value>, <wms_key2>: <wms_key2_value> ... }
    For now the implementation supports only WMS fields but can be easily expanded by
    adding <key/values> to the Dictionary below.
    """
    supported_scopes = {
        "wms": {
            "scopes": [
                ("WMSContactOrganization", "contact_organization"),
                ("WMSContactMail", "contact_mail"),
                ("WMSContactPerson", "contact_person"),
                ("WMSContactPhone", "contact_phone"),
                ("WMSContactPosition", "contact_position"),
                ("WMSFees", "fees"),
                ("WMSKeywordList", "keyword_list"),
                ("WMSOnlineResource", "online_resource"),
                ("WMSServiceAbstract", "service_abstract"),
                ("WMSServiceTitle", "service_title"),
                ("WMSUrl", "resource_url"),
            ],
            "keys": ["/"],
        }
    }

    scopes = [scope_or_scopes] if isinstance(scope_or_scopes, str) else scope_or_scopes

    for scope in scopes:

        if not scope in supported_scopes:
            supported = ", ".join(supported_scopes.keys())
            error_detail = (
                f"This scope is not supported: {scope}. Supported scopes: {supported}"
            )
            raise ValueError(error_detail)

        scope_entries = supported_scopes[scope]["scopes"]
        key_entries = supported_scopes[scope]["keys"]
        to_collect = zip_longest(scope_entries, key_entries, fillvalue=key_entries[0])

        def collect(acc, pair):
            scope, key = pair
            qgis_scope_name, our_scope_name = scope

            if "list" in qgis_scope_name.lower():
                # PyQGIS sometimes violates Liskov's substitution principle so naming tricks needed
                list_as_text = ", ".join(project.readListEntry(qgis_scope_name, key)[0])
                acc.append((our_scope_name, list_as_text))
            else:
                acc.append((our_scope_name, project.readEntry(qgis_scope_name, key)[0]))

            return acc

        return dict(reduce(collect, to_collect, []))

make_wgs84_geom_transform(project, layer)

Makes a QgisCoordinateTransform to transform a layer to EPSG:4326).

Source code in src/qgis_server_light/exporter/funcs.py
38
39
40
41
42
def make_wgs84_geom_transform(project, layer) -> Any:
    """Makes a QgisCoordinateTransform to transform a layer to EPSG:4326)."""
    sourceCrs = layer.crs()
    EPSG_4326 = QgsCoordinateReferenceSystem("EPSG:4326")
    return QgsCoordinateTransform(sourceCrs, EPSG_4326, project)