Skip to content

Exporter

exporter

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.")

cli

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

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

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

export(project: str, unify_layer_names_by_group: bool = False, output_format: str | None = None) -> None

Source code in src/qgis_server_light/exporter/cli.py
 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
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@click.option("--project", help="Absolute path to the QGIS project.")
@click.option(
    "--unify_layer_names_by_group",
    default=False,
    help="Use the full tree path to unify job_layer_definition names.",
)
@click.option(
    "--output_format",
    default="json",
    help=f"The desired output format. Allowed are {'|'.join(allowed_output_formats)}.",
)
@main.command(
    "export",
    context_settings={"max_content_width": 120},
    help=f"""
    Export a QGIS project ({"|".join(allowed_extensions)}) (1st argument) file
    to {"|".join(allowed_output_formats)} format.

    Layers referencing a pg_service need the PGSERVICEFILE environment variable so
    that QGIS can open them during the export. The cli might be called with:

      PGSERVICEFILE=<absolute-path-to-pg_service.conf> python -m qgis_server_light.exporter.cli ...
    """,
)
def export(
    project: str,
    unify_layer_names_by_group: bool = False,
    output_format: str | None = None,
) -> None:
    logging.getLogger().setLevel(logging.DEBUG)
    serializer_config = SerializerConfig(indent="  ")
    output_format = "json" if output_format is None else output_format.lower()
    if not project.lower().endswith(allowed_extensions):
        raise click.BadParameter(
            f"Allowed qgis project file extensions "
            f"are: {'|'.join(allowed_extensions)} not => {project}",
            param_hint="--project",
        )
    if output_format not in allowed_output_formats:
        raise click.BadParameter(
            f"Allowed output formats are: {'|'.join(allowed_output_formats)} "
            f"not => {output_format}",
            param_hint="--output_format",
        )
    if not os.path.isfile(project):
        raise click.BadParameter(
            f"Project file '{project}' does not exist",
            param_hint="--project",
        )

    exporter = Exporter(
        project,
        unify_layer_names_by_group=bool(unify_layer_names_by_group),
    )

    if output_format == "json":
        serializer = JsonSerializer(config=serializer_config)
    elif output_format == "xml":
        serializer = XmlSerializer(config=serializer_config)
    else:
        raise RuntimeError(f"Unexpected output format {output_format}")

    try:
        config = exporter.run()
    except ExportFailure as err:
        click.echo(serializer.render(err.get_result()))
        raise click.exceptions.Exit(code=err.EXIT_CODE) from err
    else:
        click.echo(serializer.render(config))

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/cli.py
24
25
26
27
28
29
30
@click.group
def main() -> None:
    """
    Just the central cli entry command. Currently, we don't use it, but its here
    for future content.

    """

exceptions

ExportFailure

Bases: Exception

Source code in src/qgis_server_light/exporter/exceptions.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class ExportFailure(Exception):
    EXIT_CODE = 3

    def __init__(
        self,
        *,
        messages: list[ExportMessage],
        project: Project,
        exporter: Exporter,
    ) -> None:
        super().__init__("QGIS project export failed")
        self.messages = messages
        self.project = project
        self.exporter = exporter

    def get_result(self) -> ResultWithMessages:
        return ResultWithMessages(
            project=self.project,
            exporter=self.exporter,
            messages=self.messages,
        )
EXIT_CODE = 3 class-attribute instance-attribute
exporter = exporter instance-attribute
messages = messages instance-attribute
project = project instance-attribute
__init__(*, messages: list[ExportMessage], project: Project, exporter: Exporter) -> None
Source code in src/qgis_server_light/exporter/exceptions.py
12
13
14
15
16
17
18
19
20
21
22
def __init__(
    self,
    *,
    messages: list[ExportMessage],
    project: Project,
    exporter: Exporter,
) -> None:
    super().__init__("QGIS project export failed")
    self.messages = messages
    self.project = project
    self.exporter = exporter
get_result() -> ResultWithMessages
Source code in src/qgis_server_light/exporter/exceptions.py
24
25
26
27
28
29
def get_result(self) -> ResultWithMessages:
    return ResultWithMessages(
        project=self.project,
        exporter=self.exporter,
        messages=self.messages,
    )

extract

Exporter

Source code in src/qgis_server_light/exporter/extract.py
  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
 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
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 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
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 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
 273
 274
 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
 510
 511
 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
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 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
 607
 608
 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
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
class Exporter:
    def __init__(
        self,
        qgis_project_path: str,
        unify_layer_names_by_group=False,
        unify_layer_names_by_group_separator=".",
    ):
        self.unify_layer_names_by_group_separator = unify_layer_names_by_group_separator
        self.path = qgis_project_path
        self.unify_layer_names_by_group = unify_layer_names_by_group

        # prepare QGIS instances
        self.qgis_project = self.open_qgis_project(qgis_project_path)
        self.qgis_project_tree_root = self.qgis_project.layerTreeRoot()
        self.name = self.prepare_qgis_project_name(self.qgis_project)
        self.version = self.qgis_project.lastSaveVersion()

        # prepare QSL interface instances
        self.qsl_tree = Tree()
        self.qsl_datasets = Datasets()
        self.qsl_project = Project(name=self.name, version=self.version.text())
        self.qsl_project_metadata = self.extract_metadata(self.qgis_project)
        self.qsl_config = Config(
            exporter=ExporterMeta(qgis_version=Qgis.version()),
            project=self.qsl_project,
            meta_data=self.qsl_project_metadata,
            tree=self.qsl_tree,
            datasets=self.qsl_datasets,
        )

    def run(self) -> Config:
        if project_error := self.qgis_project.error():
            self.qsl_config.error(
                project_error,
                code=ExportMessage.Code.PROJECT_READ_FAILED,
            )
            raise self.build_export_failure()
        if self.version.majorVersion() > 4:
            self.qsl_config.error(
                f"QGIS project version {self.version.text()} is not supported.",
                code=ExportMessage.Code.PROJECT_VERSION_UNSUPPORTED,
            )
            raise self.build_export_failure()
        self.walk_qgis_project_tree(self.qgis_project_tree_root, [])
        self.qsl_config.relations = self.create_qsl_relations(self.qgis_project)
        return self.qsl_config

    def walk_qgis_project_tree(
        self,
        entity: QgsLayerTreeNode,
        path: list[str],
    ):
        """
        This is a highly recursive function which walks to the qgis job_layer_definition
        tree to extract all knowledge out
        of it. It is called from itself again for each level of group like elements
        which are found.

        Args:
            entity: The QGIS projects tree node which can be a QgsLayerTree, QgsLayerTreeGroup or
                QgsLayerTreeLayer.
            path: The path is a list of string which stores the information of the current
                tree path. This is
                used to construct a string for unifying job_layer_definition names by their
                tree path.
        """
        if isinstance(entity, QgsLayerTreeLayer):
            # this is a job_layer_definition, we can extract its information
            self.extract_save_layer(
                entity,
                path,
            )
        elif isinstance(entity, (QgsLayerTreeGroup, QgsLayerTree)):
            # these are "group like" elements, we need to step into them one level deeper.
            short_name = self.get_group_short_name(entity)
            if short_name != "":
                # '' is the root of the tree, we don't want it to be part of the path
                path = path + [short_name]
            self.extract_group(
                entity,
                path,
            )
            for child in entity.children():
                # we handle all the children of the group like thing.
                self.walk_qgis_project_tree(
                    child,
                    path,
                )
        else:
            self.qsl_config.warning(
                "This element was not expected while walking QGIS project tree: "
                f"{type(entity).__name__} at {'/'.join(path)}",
                code=ExportMessage.Code.TREE_NODE_UNSUPPORTED,
            )

    def extract_group(
        self,
        group: QgsLayerTreeGroup,
        path: list[str],
    ):
        """
        Collects data pertaining to a QGIS job_layer_definition tree group. Basically
        this translates a QgsLayerTreeGroup
        into a QGIS-Server-Light TreeGroup.

        Args:
            group: The group which is handled.
            path: The path is a list of string which stores the information of the current
                tree path. This is
                used to construct a string for unifying job_layer_definition names by
                their tree path.
        """
        children = []
        for child in group.children():
            if isinstance(child, QgsLayerTreeGroup):
                children.append(
                    self.create_unified_short_name(self.get_group_short_name(child), path)
                )
            else:
                children.append(child.layer().id())
        short_name = self.create_unified_short_name(self.get_group_short_name(group), path[:-1])
        self.qsl_tree.members.append(
            TreeGroup(
                id=short_name,
                name=short_name,
                children=children,
                is_checked=group.itemVisibilityChecked(),
                is_expanded=group.isExpanded(),
            )
        )
        self.qsl_datasets.group.append(
            Group(
                id=short_name,
                name=short_name,
                title=self.get_group_title(group),
                is_checked=group.itemVisibilityChecked(),
                is_expanded=group.isExpanded(),
            )
        )

    def extract_save_layer(
        self,
        child: QgsLayerTreeLayer,
        path: list[str],
        types_from_editor_widget: bool = False,
    ):
        """Save the given job_layer_definition to the output path."""
        layer = child.layer()
        is_checked = child.itemVisibilityChecked()
        layer_type = self.get_layer_type(layer)
        if layer_type is None:
            self.qsl_config.warning(
                f"Layer type {layer.type().name} of layer "
                f"{layer.title() or layer.name()!r} is not supported.",
                code=ExportMessage.Code.LAYER_TYPE_UNSUPPORTED,
                layer_id=layer.id(),
            )
            return

        self.rewrite_datasource_with_qgis3_compatible_uri(layer)
        if not self.is_layer_valid(layer):
            error_message = (
                layer.error().summary()
                or layer.dataProvider().error().summary()
                or f"Layer with name {layer.title() or layer.name()!r} is not valid."
            )
            self.qsl_config.error(
                error_message,
                code=ExportMessage.Code.LAYER_INVALID,
                layer_id=layer.id(),
            )
            raise self.build_export_failure()

        decoded = self.extract_datasource_dict(layer)
        short_name = self.short_name(self.get_layer_short_name(child), path)
        if layer.isSpatial():
            crs = self.create_qsl_crs_from_qgs_layer(layer)
            layer_extent = self.get_layer_extent(layer)
            if layer_extent is None:
                self.qsl_config.error(
                    "Could not determine an extent for layer",
                    code=ExportMessage.Code.LAYER_EXTENT_MISSING,
                    layer_id=layer.id(),
                )
                raise self.build_export_failure()
            bbox_wgs84 = self.create_qsl_bbox_from_qgis_rectangle_wgs84(
                self.qgis_project, layer, layer_extent
            )
            bbox = self.create_qsl_bbox_from_qgis_rectangle_extent(layer_extent)
            is_spatial = True
        else:
            crs = None
            bbox_wgs84 = None
            bbox = None
            is_spatial = False

        if layer_type == "vector":
            data_provider: QgsVectorDataProvider = layer.dataProvider()
            if data_provider.isValid() and data_provider.empty():
                self.qsl_config.warning(
                    "Vector layer is empty",
                    code=ExportMessage.Code.LAYER_EMPTY,
                    layer_id=layer.id(),
                )
            if layer.providerType().lower() == "ogr":
                source = DataSource(ogr=self.create_qsl_source_ogr(decoded))
            elif layer.providerType().lower() == "postgres":
                source = DataSource(postgres=self.create_qsl_source_postgresql(decoded))
            elif layer.providerType().lower() == "wfs":
                # TODO: Correctly implement source!
                source = WfsSource()
            else:
                self.qsl_config.warning(
                    f"Unknown provider type {layer.providerType().lower()} "
                    f"for vector job_layer_definition {layer.title() or layer.name()}",
                    code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                    layer_id=layer.id(),
                )
                return
            qsl_vector_dataset_fields = self.create_qsl_fields_from_qgis_field(layer)
            self.qsl_datasets.vector.append(
                Vector(
                    name=short_name,
                    title=layer.title() or layer.name(),
                    styles=self.create_style_list(layer),
                    driver=layer.providerType(),
                    bbox_wgs84=bbox_wgs84,
                    fields=qsl_vector_dataset_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,
                    is_spatial=is_spatial,
                    is_checked=is_checked,
                    # Qgis server property WMSBackgroundLayer can only be set for raster layers
                    is_background=False,
                )
            )
        elif layer_type == "raster":
            if layer.providerType() == "gdal":
                source = DataSource(gdal=self.create_qsl_source_gdal(decoded))
            elif layer.providerType() == "wms":
                if "tileMatrixSet" in decoded:
                    source = DataSource(wmts=self.create_qsl_source_wmts(decoded))
                else:
                    if decoded.get("type") == "xyz":
                        source = DataSource(xyz=self.create_qsl_source_xyz(decoded))
                    else:
                        source = DataSource(wms=self.create_qsl_source_wms(decoded))
            elif layer.providerType() == "wcs":
                source = DataSource(wcs=self.create_qsl_source_wcs(decoded))
            else:
                self.qsl_config.warning(
                    f"Unknown provider type in raster layer: {layer.providerType().lower()}",
                    code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                    layer_id=layer.id(),
                )
                return

            self.qsl_datasets.raster.append(
                Raster(
                    name=short_name,
                    title=layer.title() or layer.name(),
                    styles=self.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(),
                    is_spatial=is_spatial,
                    is_checked=is_checked,
                    is_background=self.is_wms_background_layer(layer),
                )
            )

        elif layer_type == "custom":
            if layer.providerType().lower() in ["xyzvectortiles", "mbtilesvectortiles"]:
                source = DataSource(vector_tile=self.create_qsl_source_vector_tiles(decoded))
            else:
                # TODO: make this more configurable
                self.qsl_config.warning(
                    f"Unknown provider type: {layer.providerType().lower()} "
                    f"in layer with short_name {short_name}",
                    code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                    layer_id=layer.id(),
                )
                return
            self.qsl_datasets.custom.append(
                Custom(
                    name=short_name,
                    title=layer.title() or layer.name(),
                    styles=self.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(),
                    is_spatial=is_spatial,
                    is_checked=is_checked,
                    # Qgis server property WMSBackgroundLayer can only be set for raster layers
                    is_background=False,
                )
            )

    def short_name(self, short_name: str, path: list[str]) -> str:
        """
        Decides if to use the short name itself or the unified version by the tree path.

        Args:
            short_name: The short name either of the group or the job_layer_definition.
            path: The path is a list of string which stores the information of the current
                tree path. This is
                used to construct a string for unifying job_layer_definition names by
                their tree path.

        Returns:
            The short name itself or its unified tree path.
        """
        if self.unify_layer_names_by_group:
            return self.create_unified_short_name(short_name, path)
        else:
            return short_name

    def create_unified_short_name(self, short_name: str, path: list[str]):
        """
        Creates the unified short name, separated by the configured separator.

        Args:
            short_name: The short name either of the group or the job_layer_definition.
            path: The path is a list of string which stores the information of the current
                tree path. This is
                used to construct a string for unifying job_layer_definition names by
                their tree path.

        Returns:

        """
        short_name_parts = path + [short_name]
        return self.unify_layer_names_by_group_separator.join(short_name_parts)

    def rewrite_datasource_with_qgis3_compatible_uri(self, layer: QgsMapLayer):
        # QGIS 3 is inconsistent in how it encodes/decodes source URIs, whereas
        # QGIS 4 systematically percent-encodes reserved characters inside datasource values.
        # A project saved by QGIS >= 4 and read by a QGIS 3 build (QSL is based on
        # QGIS 3) therefore needs an unquote() pass to get clean values.
        if not Qgis.version().startswith("3."):
            return

        if self.version.majorVersion() >= 4:
            registry = QgsProviderRegistry.instance()
            original_uri = layer.source()
            qgis3_compatible_uri = registry.encodeUri(
                layer.providerType(),
                {
                    key: unquote(value) if isinstance(value, str) else value
                    for (key, value) in registry.decodeUri(
                        layer.providerType(), original_uri
                    ).items()
                },
            )
            logging.debug(
                f"Layer {layer.id()} datasource URI from QGIS 4 project is rewritten: "
                f"original={original_uri!r}, QGIS 3 compatible={qgis3_compatible_uri!r}"
            )
            layer.setDataSource(qgis3_compatible_uri)

    def extract_datasource_dict(self, layer: QgsMapLayer) -> dict:
        """
        Decodes a QGIS map job_layer_definition datasource into a dict and ensures that
        types are pythonic and pathes are
        clean for further usage.

        Args:
            layer: The job_layer_definition which the datasource should be extracted from.

        Returns:
            The decoded and cleaned datasource.
        """
        decoded = QgsProviderRegistry.instance().decodeUri(
            layer.providerType(), layer.dataProvider().dataSourceUri()
        )
        logging.debug(f"Layer source: {decoded}")
        for key in decoded:
            if str(decoded[key]) in ("None", "NULL"):
                decoded[key] = None
                continue
            if key == "path":
                # QGIS 3 returns url encoded paths, which leads to incorrect operations,
                # eg: ".%2Fdata%2Fhiroshima.mbtiles" instead of "./data/hiroshima.mbtiles"
                # For QGIS 4 projects, the value is expected to be decoded already.
                if self.version.majorVersion() <= 3:
                    decoded_path = unquote(decoded[key])
                else:
                    decoded_path = decoded[key]
                # Make path relative to the qgis_project
                decoded[key] = decoded_path.replace(f"{self.qgis_project.readPath('./')}/", "")
            else:
                decoded[key] = str(decoded[key])
        return decoded

    @staticmethod
    def create_qsl_field_from_qgis_field(
        field: QgsField,
        is_primary_key: bool,
        is_generated: bool = False,
    ) -> Field:
        attribute_type_xml = Exporter.obtain_simple_types_from_qgis_field_xml(field)
        (
            editor_widget_type,
            editor_widget_type_wfs,
            editor_widget_type_json,
            editor_widget_type_json_format,
        ) = Exporter.obtain_editor_widget_type_from_qgis_field(field)
        (
            attribute_type_json,
            attribute_type_json_format,
        ) = Exporter.obtain_simple_types_from_qgis_field_json(field)
        return Field(
            is_primary_key=is_primary_key,
            is_generated=is_generated,
            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=not is_primary_key and Exporter.obtain_nullable(field),
            length=Exporter.provide_field_length(field),
            precision=Exporter.provide_field_precision(field),
            editor_widget_type=editor_widget_type,
            editor_widget_type_wfs=editor_widget_type_wfs,
            editor_widget_type_oapif=editor_widget_type_json,
            editor_widget_type_oapif_format=editor_widget_type_json_format,
            editor_widget=Exporter.create_qsl_editor_widget(field.editorWidgetSetup()),
            constraints=Exporter.create_qsl_field_constraints(field),
        )

    @staticmethod
    def create_qsl_editor_widget(setup: QgsEditorWidgetSetup) -> EditorWidget | None:
        """
        Translates the configuration of the editor widgets which define value lists or
        domains. Layer and relation references are exported as they are, resolving
        them is left to the consumer!

        Args:
            setup: The editor widget setup of a field of an `QgsVectorLayer`.

        Returns:
            The editor widget configuration or None if the widget type is not exported.
        """
        editor_widget_type = setup.type()
        config = setup.config()
        if editor_widget_type == "ValueMap":
            return EditorWidget(value_map=Exporter.create_qsl_value_map(config))
        elif editor_widget_type == "ValueRelation":
            return EditorWidget(value_relation=Exporter.create_qsl_value_relation(config))
        elif editor_widget_type == "RelationReference":
            return EditorWidget(
                relation_reference=RelationReference(relation_id=config.get("Relation", ""))
            )
        elif editor_widget_type == "Range":
            return EditorWidget(range=Exporter.create_qsl_range(config))
        return None

    @staticmethod
    def create_qsl_value_map(config: dict) -> ValueMap:
        """
        Reads the value map as QGIS knows them (2 kinds): the current one, a list of single
        entry dicts, and the old one, a single dict. Both map description to key, the
        key `QgsValueMapFieldFormatter.NULL_VALUE` stands for NULL.

        Args:
            config: The editor widget configuration of a `ValueMap` widget.

        Returns:
            The value map in the order defined in QGIS.
        """
        value_map_config = config.get("map", [])
        if isinstance(value_map_config, dict):
            value_map_config = [value_map_config]
        value_map = ValueMap()
        for value_map_item in value_map_config:
            for description, key in value_map_item.items():
                if key == QgsValueMapFieldFormatter.NULL_VALUE:
                    value_map.null_representation = description
                else:
                    value_map.entries.append(ValueMapEntry(key=str(key), description=description))
        return value_map

    @staticmethod
    def create_qsl_value_relation(config: dict) -> ValueRelation:
        """Builder function to create the interface instance."""
        return ValueRelation(
            layer_id=config.get("Layer", ""),
            key_field=config.get("Key", ""),
            value_field=config.get("Value", ""),
            filter_expression=config.get("FilterExpression") or None,
            allow_multi=bool(config.get("AllowMulti", False)),
            order_by_value=bool(config.get("OrderByValue", False)),
        )

    @staticmethod
    def create_qsl_range(config: dict) -> Range:
        """Builder function to create the interface instance."""
        return Range(
            minimum=Exporter.provide_float(config.get("Min")),
            maximum=Exporter.provide_float(config.get("Max")),
            step=Exporter.provide_float(config.get("Step")),
        )

    @staticmethod
    def provide_float(value) -> float | None:
        """Just an internal helper"""
        if value is None:
            return None
        return float(value)

    @staticmethod
    def create_qsl_field_constraints(field: QgsField) -> FieldConstraints:
        """Builder function to create the interface instance."""
        field_constraints = field.constraints()
        constraints = field_constraints.constraints()
        return FieldConstraints(
            not_null=bool(constraints & QgsFieldConstraints.Constraint.ConstraintNotNull),
            unique=bool(constraints & QgsFieldConstraints.Constraint.ConstraintUnique),
            expression=field_constraints.constraintExpression() or None,
        )

    @staticmethod
    def create_qsl_relations(project: QgsProject) -> list[Relation]:
        """
        Translates the relations of the project. All relations are exported, also the
        ones whose layers are not part of the export.

        Args:
            project: The instantiated QGIS project.

        Returns:
            The relations of the project.
        """
        relations = []
        for relation in project.relationManager().relations().values():
            relations.append(
                Relation(
                    id=relation.id(),
                    name=relation.name(),
                    referencing_layer_id=relation.referencingLayerId(),
                    referenced_layer_id=relation.referencedLayerId(),
                    field_pairs=[
                        RelationFieldPair(
                            referencing_field=referencing_field,
                            referenced_field=referenced_field,
                        )
                        for referencing_field, referenced_field in relation.fieldPairs().items()
                    ],
                    strength=relation.strength().name,
                )
            )
        return relations

    @staticmethod
    def obtain_nullable(field: QgsField) -> bool:
        """

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

        Returns:
            False if the field carries a NotNull constraint (possibly combined with
            others like Unique or Expression), True otherwise.
        """
        constraints = field.constraints().constraints()
        return not constraints & QgsFieldConstraints.Constraint.ConstraintNotNull

    @staticmethod
    def provide_field_length(field: QgsField) -> int | None:
        length = field.length()
        if length > 0:
            return length
        else:
            return None

    @staticmethod
    def provide_field_precision(field: QgsField) -> int | None:
        precision = field.precision()
        if precision > 0:
            return precision
        else:
            return None

    def create_qsl_fields_from_qgis_field(
        self,
        layer: QgsVectorLayer,
    ) -> list[Field]:
        fields = []
        provider = layer.dataProvider()
        pk_indexes = provider.pkAttributeIndexes()
        for field_index, field in enumerate(layer.fields().toList()):
            is_primary_key = field_index in pk_indexes
            qsl_field = self.create_qsl_field_from_qgis_field(
                field,
                is_primary_key,
                is_generated=is_primary_key and self.obtain_is_generated(provider, field_index),
            )
            if (
                qsl_field.editor_widget_type
                and qsl_field.editor_widget_type_wfs is None
                and qsl_field.editor_widget_type_oapif is None
                and qsl_field.editor_widget_type_oapif_format is None
            ):
                self.qsl_config.warning(
                    f"Editor widget type {qsl_field.editor_widget_type!r} for field "
                    f"{field.name()!r} was not handled as expected.",
                    code=ExportMessage.Code.FIELD_EDITOR_WIDGET_TYPE_UNSUPPORTED,
                    layer_id=layer.id(),
                )
            fields.append(qsl_field)
        return fields

    @staticmethod
    def obtain_is_generated(provider, field_index: int) -> bool:
        # the OGR provider (GeoPackage fid, ...) lets GDAL assign the identifier on insert,
        # other providers tell it with a default value, e.g. a sequence
        if provider.name() == "ogr":
            return True
        return bool(provider.defaultValueClause(field_index))

    @staticmethod
    def obtain_simple_types_from_qgis_field_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"

    @staticmethod
    def is_wms_background_layer(layer: QgsMapLayer) -> bool:
        return bool(layer.customProperty("WMSBackgroundLayer", False))

    @staticmethod
    def get_group_title(group: QgsLayerTreeGroup) -> str:
        if group.customProperty("wmsTitle"):
            return group.customProperty("wmsTitle")
        elif hasattr(group, "groupLayer"):  # noqa: SIM102
            # since QGIS 3.38
            if (
                group.groupLayer()
                and group.groupLayer().serverProperties()
                and group.groupLayer().serverProperties().title()
            ):
                return group.groupLayer().serverProperties().title()
        return group.name()

    @staticmethod
    def get_group_short_name(group: QgsLayerTreeGroup) -> str:
        if group.customProperty("wmsShortName"):
            return group.customProperty("wmsShortName")
        elif hasattr(group, "groupLayer"):  # noqa: SIM102
            # since QGIS 3.38
            if (
                group.groupLayer()
                and group.groupLayer().serverProperties()
                and group.groupLayer().serverProperties().shortName()
            ):
                return group.groupLayer().serverProperties().shortName()
        short_name = Exporter.sanitize_name(group.name(), lower=True)
        if short_name == "_":
            # this is the tree root, we return empty string here
            return ""
        return short_name

    @staticmethod
    def sanitize_name(raw: str, lower: bool = False) -> str:
        """
        Transforms an arbitrary string into a WMS/WFS and URL compatible short name for a
        job_layer_definition or group.

        Steps:
        1. Unicode‑NFD → ASCII‑transliteration (removes umlauts/diacritics).
        2. All chars, which are NOT [A‑Za‑z0‑9_.‑], will be replaced by '_' ersetzen.
        3. Reduce multiple underscore '_' to a single one.
        4. Remove leading '_', '.', '-'.
        5. If the string is empty OR does not start with a letter OR not start with '_',
           a leading '_' will be added.
        6. Optional all will be converted to lowercase (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

    @staticmethod
    def obtain_editor_widget_type_from_qgis_field(
        field: QgsField,
    ) -> tuple[str, str, str, str] | tuple[str, None, None, 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()
        editor_widget_type = setup.type()
        if editor_widget_type == "DateTime":
            field_format = config.get(
                "field_format", QgsDateTimeFieldFormatter.defaultFormat(attribute_type)
            )
            if field_format == QgsDateTimeFieldFormatter.TIME_FORMAT:
                return editor_widget_type, "time", "string", "time"
            elif field_format == QgsDateTimeFieldFormatter.DATE_FORMAT:
                return editor_widget_type, "date", "string", "date"
            elif (
                field_format == QgsDateTimeFieldFormatter.DATETIME_FORMAT
                or field_format == QgsDateTimeFieldFormatter.QT_ISO_FORMAT
            ):
                return editor_widget_type, "dateTime", "string", "date-time"
        elif editor_widget_type == "Range":
            if config.get("Precision"):
                config_precision = int(config["Precision"])
                if config_precision != field.precision():
                    if config_precision == 0:
                        return editor_widget_type, "integer", "integer", "int64"
                    else:
                        return editor_widget_type, "decimal", "number", "double"

        return editor_widget_type, None, None, None

    @staticmethod
    def obtain_simple_types_from_qgis_field_json(
        field: QgsField,
    ) -> tuple[str, str] | tuple[str, None]:
        """
        Delivers the type match for json based on the field QgsField type.

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

        Returns:
            Unified type name and format in a tuple.
        """
        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:
            # we handle all unknown types as string. Since its for JavaScript, this should be safe.
            return "string", None

    @staticmethod
    def create_qsl_source_wms(datasource: dict) -> WmsSource:
        return WmsSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_vector_tiles(datasource: dict) -> VectorTileSource:
        return VectorTileSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_xyz(datasource: dict) -> XYZSource:
        return XYZSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_wmts(datasource: dict) -> WmtsSource:
        return WmtsSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_wcs(datasource: dict) -> WcsSource:
        return WcsSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_gdal(datasource: dict) -> GdalSource:
        return GdalSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_ogr(datasource: dict) -> OgrSource:
        return OgrSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_postgresql(datasource: dict) -> PostgresSource:
        """
        Creates the QSL postgres source from the datasource as it is stored in the
        QGIS project. A referenced pg_service is NOT resolved: connection info and
        credentials stay in the pg_service.conf (PGSERVICEFILE) and are resolved by
        libpq at connection time on the consumer side.

        Args:
            datasource: The decoded and cleaned datasource of the layer. Its sslmode,
                if any, is the stringified QGIS int (e.g. "3" for require).

        Returns:
            The QSL postgres source.
        """
        postgres_source = PostgresSource.from_qgis_decoded_uri(datasource)
        if postgres_source.sslmode is not None:
            postgres_source.ssl_mode_text = Exporter.sslmode_int_to_str(postgres_source.sslmode)
        return postgres_source

    @staticmethod
    def sslmode_int_to_str(ssl_mode: int) -> str:
        """
        Mapper to map ssl modes from QGIS int to plain postgres.

        Args:
            ssl_mode: The ssl mode of the datasource as a int value matching one of
                https://qgis.org/pyqgis/3.44/core/QgsDataSourceUri.html#qgis.core.QgsDataSourceUri.SslMode

        Returns:
            The string representation of the ssl mode as it is used by postgres connections.
        """
        return QgsDataSourceUri.encodeSslMode(int(ssl_mode))

    @staticmethod
    def create_qsl_crs_from_qgs_layer(layer: QgsMapLayer) -> Crs:
        """
        Translates the QGIS job_layer_definition crs information into an instance of the
        QGIS-Server-Light interface Crs
        instance.

        Args:
            layer: The job_layer_definition to take the crs information from.

        Returns:
            The instance of the QSL interface Crs.
        """
        crs = layer.dataProvider().crs()
        if not crs.isValid():
            # some providers (e.g. PostGIS geometry columns without SRID) report no CRS,
            # the project CRS of the layer is the one the data is shown in
            crs = layer.crs()
        return create_qsl_crs(crs)

    @staticmethod
    def get_layer_short_name(layer: QgsLayerTreeLayer) -> str:
        """
        This method determines which name is used as the short name of the job_layer_definition.

        Args:
            layer: The job_layer_definition which the short name should be derived from.

        Returns:
            The short name.
        """
        if layer.layer().shortName():
            return layer.layer().shortName()
        elif (
            hasattr(layer.layer(), "serverProperties")
            and layer.layer().serverProperties().shortName()
        ):
            return layer.layer().serverProperties().shortName()
        return layer.layer().id()

    @staticmethod
    def make_wgs84_geom_transform(project, layer) -> QgsCoordinateTransform:
        """
        Creates a QgisCoordinateTransform context to transform a job_layer_definition
        to EPSG:4326 aka wgs84.

        Args:
            project: The QGIS project instance.
            layer: The job_layer_definition which's extent should be reprojected.

        Returns:
            The QGIS transformation context.
        """
        source_crs = layer.crs()
        epsg_4326 = QgsCoordinateReferenceSystem("EPSG:4326")
        return QgsCoordinateTransform(source_crs, epsg_4326, project)

    def create_qsl_bbox_from_qgis_rectangle_wgs84(
        self, project: QgsProject, layer: QgsMapLayer, extent: QgsRectangle
    ) -> BBox:
        """
        Reprojects the job_layer_definition's extent using WGS84.

        Args:
            project: The QGIS project instance for projection context.
            layer: The job_layer_definition which for the projection context.
            extent: The extent which will be reprojected.

        Returns:
            The QSL bbox reprojected to WGS84.
        """
        try:
            transformation_context = Exporter.make_wgs84_geom_transform(project, layer)
            reprojected_extent = transformation_context.transform(extent)
        except QgsCsException as err:
            self.qsl_config.error(
                f"Layer extent could not be reprojected from "
                f"{layer.crs().authid()} to EPSG:4326: {err}",
                code=ExportMessage.Code.LAYER_EXTENT_REPROJECTION_FAILED,
                layer_id=layer.id(),
            )
            raise self.build_export_failure() from err
        return self.create_qsl_bbox_from_qgis_rectangle_extent(reprojected_extent)

    @staticmethod
    def create_qsl_bbox_from_qgis_rectangle_extent(extent: QgsRectangle) -> BBox:
        return BBox(
            x_min=extent.xMinimum(),
            x_max=extent.xMaximum(),
            y_min=extent.yMinimum(),
            y_max=extent.yMaximum(),
        )

    @staticmethod
    def get_project_extent(project: QgsProject) -> QgsReferencedRectangle | None:
        """WMS advertised extent, else View Settings full extent, else project CRS area of use."""
        wms = QgsServerProjectUtils.wmsExtent(project)
        if not wms.isNull():
            return QgsReferencedRectangle(wms, project.crs())

        full = project.viewSettings().fullExtent()
        if not full.isNull():
            return full

        crs_bounds = project.crs().bounds()  # area of use, always in EPSG:4326
        if not crs_bounds.isNull():
            return QgsReferencedRectangle(crs_bounds, QgsCoordinateReferenceSystem("EPSG:4326"))

        return None

    def get_layer_extent(self, layer: QgsMapLayer) -> QgsReferencedRectangle | None:
        """Layer extent in the layer CRS, else the project fallback reprojected into it."""
        ext = layer.extent()
        if not ext.isNull() and ext.isFinite():
            return QgsReferencedRectangle(ext, layer.crs())

        project = layer.project()
        fallback = self.get_project_extent(project) if project else None
        if fallback is None:
            return None

        ct = QgsCoordinateTransform(fallback.crs(), layer.crs(), project.transformContext())
        try:
            transformed = ct.transformBoundingBox(fallback)
        except QgsCsException as err:
            self.qsl_config.error(
                "Layer extent could not be determined by the data provider and the "
                f"project fallback extent could not be reprojected from "
                f"{fallback.crs().authid()} to {layer.crs().authid()}: {err}",
                code=ExportMessage.Code.LAYER_EXTENT_REPROJECTION_FAILED,
                layer_id=layer.id(),
            )
            raise self.build_export_failure() from err

        self.qsl_config.warning(
            "Layer extent could not be determined by the data provider "
            "and is derived from the project instead.",
            code=ExportMessage.Code.LAYER_EXTENT_FROM_PROJECT,
            layer_id=layer.id(),
        )
        return QgsReferencedRectangle(transformed, layer.crs())

    @staticmethod
    def get_layer_type(layer: QgsMapLayer) -> str | None:
        """
        Gets the type of the given Qgis job_layer_definition as a string if the type is supported.
        This is to flatten the
        understanding of layers from qgis into something we can handle.

        Args:
            layer: The job_layer_definition to decide the type for.

        Returns:
            "raster", "vector" or "custom" if a job_layer_definition matched and None otherwise.
        """
        if isinstance(layer, QgsRasterLayer):
            return "raster"
        elif isinstance(layer, QgsVectorLayer):
            return "vector"
        elif isinstance(
            layer, (QgsVectorTileLayer, QgsTiledSceneLayer, QgsPointCloudLayer, QgsMeshLayer)
        ):
            return "custom"
        return None

    @staticmethod
    def is_layer_valid(layer: QgsMapLayer) -> bool:
        if not layer.isValid():
            logging.debug(f"Layer error: {layer.error().summary()}")
            return False
        if not layer.dataProvider().isValid():
            logging.debug(f"Data provider error: {layer.dataProvider().error().summary()}")
            return False
        return True

    @staticmethod
    def open_qgis_project(path_to_project: str) -> QgsProject:
        """


        Args:
            path_to_project: The absolute path on the file system where the project
            can be read from.

        Returns:
            The opened project (read).
        """
        project = QgsProject.instance()
        project.read(path_to_project)
        return project

    @staticmethod
    def prepare_qgis_project_name(project: QgsProject) -> str:
        """


        Args:
            project: The instantiated QGIS project.

        Returns:
            Project name
        """
        return project.title() or project.baseName()

    @staticmethod
    def extract_metadata(project: QgsProject) -> MetaData:
        """
        Creates a QSL interface instance for metadate pulled out of the QGIS project.

        Args:
            project: The instantiated QGIS project.

        Returns:
            The metadata interface instance.
        """
        _meta = project.metadata()
        wms_entries = Exporter.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=[link.url for link in _meta.links()],
        )

    @staticmethod
    def get_project_server_entries(project, scope_or_scopes: 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 scope not 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, []))

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

    def build_export_failure(self):
        return ExportFailure(
            project=self.qsl_config.project,
            exporter=self.qsl_config.exporter,
            messages=self.qsl_config.messages,
        )
name = self.prepare_qgis_project_name(self.qgis_project) instance-attribute
path = qgis_project_path instance-attribute
qgis_project = self.open_qgis_project(qgis_project_path) instance-attribute
qgis_project_tree_root = self.qgis_project.layerTreeRoot() instance-attribute
qsl_config = Config(exporter=(ExporterMeta(qgis_version=(Qgis.version()))), project=(self.qsl_project), meta_data=(self.qsl_project_metadata), tree=(self.qsl_tree), datasets=(self.qsl_datasets)) instance-attribute
qsl_datasets = Datasets() instance-attribute
qsl_project = Project(name=(self.name), version=(self.version.text())) instance-attribute
qsl_project_metadata = self.extract_metadata(self.qgis_project) instance-attribute
qsl_tree = Tree() instance-attribute
unify_layer_names_by_group = unify_layer_names_by_group instance-attribute
unify_layer_names_by_group_separator = unify_layer_names_by_group_separator instance-attribute
version = self.qgis_project.lastSaveVersion() instance-attribute
__init__(qgis_project_path: str, unify_layer_names_by_group=False, unify_layer_names_by_group_separator='.')
Source code in src/qgis_server_light/exporter/extract.py
 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
def __init__(
    self,
    qgis_project_path: str,
    unify_layer_names_by_group=False,
    unify_layer_names_by_group_separator=".",
):
    self.unify_layer_names_by_group_separator = unify_layer_names_by_group_separator
    self.path = qgis_project_path
    self.unify_layer_names_by_group = unify_layer_names_by_group

    # prepare QGIS instances
    self.qgis_project = self.open_qgis_project(qgis_project_path)
    self.qgis_project_tree_root = self.qgis_project.layerTreeRoot()
    self.name = self.prepare_qgis_project_name(self.qgis_project)
    self.version = self.qgis_project.lastSaveVersion()

    # prepare QSL interface instances
    self.qsl_tree = Tree()
    self.qsl_datasets = Datasets()
    self.qsl_project = Project(name=self.name, version=self.version.text())
    self.qsl_project_metadata = self.extract_metadata(self.qgis_project)
    self.qsl_config = Config(
        exporter=ExporterMeta(qgis_version=Qgis.version()),
        project=self.qsl_project,
        meta_data=self.qsl_project_metadata,
        tree=self.qsl_tree,
        datasets=self.qsl_datasets,
    )
build_export_failure()
Source code in src/qgis_server_light/exporter/extract.py
1279
1280
1281
1282
1283
1284
def build_export_failure(self):
    return ExportFailure(
        project=self.qsl_config.project,
        exporter=self.qsl_config.exporter,
        messages=self.qsl_config.messages,
    )
create_qsl_bbox_from_qgis_rectangle_extent(extent: QgsRectangle) -> BBox staticmethod
Source code in src/qgis_server_light/exporter/extract.py
1055
1056
1057
1058
1059
1060
1061
1062
@staticmethod
def create_qsl_bbox_from_qgis_rectangle_extent(extent: QgsRectangle) -> BBox:
    return BBox(
        x_min=extent.xMinimum(),
        x_max=extent.xMaximum(),
        y_min=extent.yMinimum(),
        y_max=extent.yMaximum(),
    )
create_qsl_bbox_from_qgis_rectangle_wgs84(project: QgsProject, layer: QgsMapLayer, extent: QgsRectangle) -> BBox

Reprojects the job_layer_definition's extent using WGS84.

Parameters:

  • project (QgsProject) –

    The QGIS project instance for projection context.

  • layer (QgsMapLayer) –

    The job_layer_definition which for the projection context.

  • extent (QgsRectangle) –

    The extent which will be reprojected.

Returns:

  • BBox –

    The QSL bbox reprojected to WGS84.

Source code in src/qgis_server_light/exporter/extract.py
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
def create_qsl_bbox_from_qgis_rectangle_wgs84(
    self, project: QgsProject, layer: QgsMapLayer, extent: QgsRectangle
) -> BBox:
    """
    Reprojects the job_layer_definition's extent using WGS84.

    Args:
        project: The QGIS project instance for projection context.
        layer: The job_layer_definition which for the projection context.
        extent: The extent which will be reprojected.

    Returns:
        The QSL bbox reprojected to WGS84.
    """
    try:
        transformation_context = Exporter.make_wgs84_geom_transform(project, layer)
        reprojected_extent = transformation_context.transform(extent)
    except QgsCsException as err:
        self.qsl_config.error(
            f"Layer extent could not be reprojected from "
            f"{layer.crs().authid()} to EPSG:4326: {err}",
            code=ExportMessage.Code.LAYER_EXTENT_REPROJECTION_FAILED,
            layer_id=layer.id(),
        )
        raise self.build_export_failure() from err
    return self.create_qsl_bbox_from_qgis_rectangle_extent(reprojected_extent)
create_qsl_crs_from_qgs_layer(layer: QgsMapLayer) -> Crs staticmethod

Translates the QGIS job_layer_definition crs information into an instance of the QGIS-Server-Light interface Crs instance.

Parameters:

  • layer (QgsMapLayer) –

    The job_layer_definition to take the crs information from.

Returns:

  • Crs –

    The instance of the QSL interface Crs.

Source code in src/qgis_server_light/exporter/extract.py
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
@staticmethod
def create_qsl_crs_from_qgs_layer(layer: QgsMapLayer) -> Crs:
    """
    Translates the QGIS job_layer_definition crs information into an instance of the
    QGIS-Server-Light interface Crs
    instance.

    Args:
        layer: The job_layer_definition to take the crs information from.

    Returns:
        The instance of the QSL interface Crs.
    """
    crs = layer.dataProvider().crs()
    if not crs.isValid():
        # some providers (e.g. PostGIS geometry columns without SRID) report no CRS,
        # the project CRS of the layer is the one the data is shown in
        crs = layer.crs()
    return create_qsl_crs(crs)
create_qsl_editor_widget(setup: QgsEditorWidgetSetup) -> EditorWidget | None staticmethod

Translates the configuration of the editor widgets which define value lists or domains. Layer and relation references are exported as they are, resolving them is left to the consumer!

Parameters:

  • setup (QgsEditorWidgetSetup) –

    The editor widget setup of a field of an QgsVectorLayer.

Returns:

  • EditorWidget | None –

    The editor widget configuration or None if the widget type is not exported.

Source code in src/qgis_server_light/exporter/extract.py
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
@staticmethod
def create_qsl_editor_widget(setup: QgsEditorWidgetSetup) -> EditorWidget | None:
    """
    Translates the configuration of the editor widgets which define value lists or
    domains. Layer and relation references are exported as they are, resolving
    them is left to the consumer!

    Args:
        setup: The editor widget setup of a field of an `QgsVectorLayer`.

    Returns:
        The editor widget configuration or None if the widget type is not exported.
    """
    editor_widget_type = setup.type()
    config = setup.config()
    if editor_widget_type == "ValueMap":
        return EditorWidget(value_map=Exporter.create_qsl_value_map(config))
    elif editor_widget_type == "ValueRelation":
        return EditorWidget(value_relation=Exporter.create_qsl_value_relation(config))
    elif editor_widget_type == "RelationReference":
        return EditorWidget(
            relation_reference=RelationReference(relation_id=config.get("Relation", ""))
        )
    elif editor_widget_type == "Range":
        return EditorWidget(range=Exporter.create_qsl_range(config))
    return None
create_qsl_field_constraints(field: QgsField) -> FieldConstraints staticmethod

Builder function to create the interface instance.

Source code in src/qgis_server_light/exporter/extract.py
613
614
615
616
617
618
619
620
621
622
@staticmethod
def create_qsl_field_constraints(field: QgsField) -> FieldConstraints:
    """Builder function to create the interface instance."""
    field_constraints = field.constraints()
    constraints = field_constraints.constraints()
    return FieldConstraints(
        not_null=bool(constraints & QgsFieldConstraints.Constraint.ConstraintNotNull),
        unique=bool(constraints & QgsFieldConstraints.Constraint.ConstraintUnique),
        expression=field_constraints.constraintExpression() or None,
    )
create_qsl_field_from_qgis_field(field: QgsField, is_primary_key: bool, is_generated: bool = False) -> Field staticmethod
Source code in src/qgis_server_light/exporter/extract.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
@staticmethod
def create_qsl_field_from_qgis_field(
    field: QgsField,
    is_primary_key: bool,
    is_generated: bool = False,
) -> Field:
    attribute_type_xml = Exporter.obtain_simple_types_from_qgis_field_xml(field)
    (
        editor_widget_type,
        editor_widget_type_wfs,
        editor_widget_type_json,
        editor_widget_type_json_format,
    ) = Exporter.obtain_editor_widget_type_from_qgis_field(field)
    (
        attribute_type_json,
        attribute_type_json_format,
    ) = Exporter.obtain_simple_types_from_qgis_field_json(field)
    return Field(
        is_primary_key=is_primary_key,
        is_generated=is_generated,
        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=not is_primary_key and Exporter.obtain_nullable(field),
        length=Exporter.provide_field_length(field),
        precision=Exporter.provide_field_precision(field),
        editor_widget_type=editor_widget_type,
        editor_widget_type_wfs=editor_widget_type_wfs,
        editor_widget_type_oapif=editor_widget_type_json,
        editor_widget_type_oapif_format=editor_widget_type_json_format,
        editor_widget=Exporter.create_qsl_editor_widget(field.editorWidgetSetup()),
        constraints=Exporter.create_qsl_field_constraints(field),
    )
create_qsl_fields_from_qgis_field(layer: QgsVectorLayer) -> list[Field]
Source code in src/qgis_server_light/exporter/extract.py
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
def create_qsl_fields_from_qgis_field(
    self,
    layer: QgsVectorLayer,
) -> list[Field]:
    fields = []
    provider = layer.dataProvider()
    pk_indexes = provider.pkAttributeIndexes()
    for field_index, field in enumerate(layer.fields().toList()):
        is_primary_key = field_index in pk_indexes
        qsl_field = self.create_qsl_field_from_qgis_field(
            field,
            is_primary_key,
            is_generated=is_primary_key and self.obtain_is_generated(provider, field_index),
        )
        if (
            qsl_field.editor_widget_type
            and qsl_field.editor_widget_type_wfs is None
            and qsl_field.editor_widget_type_oapif is None
            and qsl_field.editor_widget_type_oapif_format is None
        ):
            self.qsl_config.warning(
                f"Editor widget type {qsl_field.editor_widget_type!r} for field "
                f"{field.name()!r} was not handled as expected.",
                code=ExportMessage.Code.FIELD_EDITOR_WIDGET_TYPE_UNSUPPORTED,
                layer_id=layer.id(),
            )
        fields.append(qsl_field)
    return fields
create_qsl_range(config: dict) -> Range staticmethod

Builder function to create the interface instance.

Source code in src/qgis_server_light/exporter/extract.py
597
598
599
600
601
602
603
604
@staticmethod
def create_qsl_range(config: dict) -> Range:
    """Builder function to create the interface instance."""
    return Range(
        minimum=Exporter.provide_float(config.get("Min")),
        maximum=Exporter.provide_float(config.get("Max")),
        step=Exporter.provide_float(config.get("Step")),
    )
create_qsl_relations(project: QgsProject) -> list[Relation] staticmethod

Translates the relations of the project. All relations are exported, also the ones whose layers are not part of the export.

Parameters:

  • project (QgsProject) –

    The instantiated QGIS project.

Returns:

  • list[Relation] –

    The relations of the project.

Source code in src/qgis_server_light/exporter/extract.py
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
653
654
@staticmethod
def create_qsl_relations(project: QgsProject) -> list[Relation]:
    """
    Translates the relations of the project. All relations are exported, also the
    ones whose layers are not part of the export.

    Args:
        project: The instantiated QGIS project.

    Returns:
        The relations of the project.
    """
    relations = []
    for relation in project.relationManager().relations().values():
        relations.append(
            Relation(
                id=relation.id(),
                name=relation.name(),
                referencing_layer_id=relation.referencingLayerId(),
                referenced_layer_id=relation.referencedLayerId(),
                field_pairs=[
                    RelationFieldPair(
                        referencing_field=referencing_field,
                        referenced_field=referenced_field,
                    )
                    for referencing_field, referenced_field in relation.fieldPairs().items()
                ],
                strength=relation.strength().name,
            )
        )
    return relations
create_qsl_source_gdal(datasource: dict) -> GdalSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
929
930
931
@staticmethod
def create_qsl_source_gdal(datasource: dict) -> GdalSource:
    return GdalSource.from_qgis_decoded_uri(datasource)
create_qsl_source_ogr(datasource: dict) -> OgrSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
933
934
935
@staticmethod
def create_qsl_source_ogr(datasource: dict) -> OgrSource:
    return OgrSource.from_qgis_decoded_uri(datasource)
create_qsl_source_postgresql(datasource: dict) -> PostgresSource staticmethod

Creates the QSL postgres source from the datasource as it is stored in the QGIS project. A referenced pg_service is NOT resolved: connection info and credentials stay in the pg_service.conf (PGSERVICEFILE) and are resolved by libpq at connection time on the consumer side.

Parameters:

  • datasource (dict) –

    The decoded and cleaned datasource of the layer. Its sslmode, if any, is the stringified QGIS int (e.g. "3" for require).

Returns:

Source code in src/qgis_server_light/exporter/extract.py
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
@staticmethod
def create_qsl_source_postgresql(datasource: dict) -> PostgresSource:
    """
    Creates the QSL postgres source from the datasource as it is stored in the
    QGIS project. A referenced pg_service is NOT resolved: connection info and
    credentials stay in the pg_service.conf (PGSERVICEFILE) and are resolved by
    libpq at connection time on the consumer side.

    Args:
        datasource: The decoded and cleaned datasource of the layer. Its sslmode,
            if any, is the stringified QGIS int (e.g. "3" for require).

    Returns:
        The QSL postgres source.
    """
    postgres_source = PostgresSource.from_qgis_decoded_uri(datasource)
    if postgres_source.sslmode is not None:
        postgres_source.ssl_mode_text = Exporter.sslmode_int_to_str(postgres_source.sslmode)
    return postgres_source
create_qsl_source_vector_tiles(datasource: dict) -> VectorTileSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
913
914
915
@staticmethod
def create_qsl_source_vector_tiles(datasource: dict) -> VectorTileSource:
    return VectorTileSource.from_qgis_decoded_uri(datasource)
create_qsl_source_wcs(datasource: dict) -> WcsSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
925
926
927
@staticmethod
def create_qsl_source_wcs(datasource: dict) -> WcsSource:
    return WcsSource.from_qgis_decoded_uri(datasource)
create_qsl_source_wms(datasource: dict) -> WmsSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
909
910
911
@staticmethod
def create_qsl_source_wms(datasource: dict) -> WmsSource:
    return WmsSource.from_qgis_decoded_uri(datasource)
create_qsl_source_wmts(datasource: dict) -> WmtsSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
921
922
923
@staticmethod
def create_qsl_source_wmts(datasource: dict) -> WmtsSource:
    return WmtsSource.from_qgis_decoded_uri(datasource)
create_qsl_source_xyz(datasource: dict) -> XYZSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
917
918
919
@staticmethod
def create_qsl_source_xyz(datasource: dict) -> XYZSource:
    return XYZSource.from_qgis_decoded_uri(datasource)
create_qsl_value_map(config: dict) -> ValueMap staticmethod

Reads the value map as QGIS knows them (2 kinds): the current one, a list of single entry dicts, and the old one, a single dict. Both map description to key, the key QgsValueMapFieldFormatter.NULL_VALUE stands for NULL.

Parameters:

  • config (dict) –

    The editor widget configuration of a ValueMap widget.

Returns:

  • ValueMap –

    The value map in the order defined in QGIS.

Source code in src/qgis_server_light/exporter/extract.py
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@staticmethod
def create_qsl_value_map(config: dict) -> ValueMap:
    """
    Reads the value map as QGIS knows them (2 kinds): the current one, a list of single
    entry dicts, and the old one, a single dict. Both map description to key, the
    key `QgsValueMapFieldFormatter.NULL_VALUE` stands for NULL.

    Args:
        config: The editor widget configuration of a `ValueMap` widget.

    Returns:
        The value map in the order defined in QGIS.
    """
    value_map_config = config.get("map", [])
    if isinstance(value_map_config, dict):
        value_map_config = [value_map_config]
    value_map = ValueMap()
    for value_map_item in value_map_config:
        for description, key in value_map_item.items():
            if key == QgsValueMapFieldFormatter.NULL_VALUE:
                value_map.null_representation = description
            else:
                value_map.entries.append(ValueMapEntry(key=str(key), description=description))
    return value_map
create_qsl_value_relation(config: dict) -> ValueRelation staticmethod

Builder function to create the interface instance.

Source code in src/qgis_server_light/exporter/extract.py
585
586
587
588
589
590
591
592
593
594
595
@staticmethod
def create_qsl_value_relation(config: dict) -> ValueRelation:
    """Builder function to create the interface instance."""
    return ValueRelation(
        layer_id=config.get("Layer", ""),
        key_field=config.get("Key", ""),
        value_field=config.get("Value", ""),
        filter_expression=config.get("FilterExpression") or None,
        allow_multi=bool(config.get("AllowMulti", False)),
        order_by_value=bool(config.get("OrderByValue", False)),
    )
create_style_list(qgs_layer: QgsMapLayer) -> list[Style] staticmethod
Source code in src/qgis_server_light/exporter/extract.py
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
@staticmethod
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(short_name: str, path: list[str])

Creates the unified short name, separated by the configured separator.

Parameters:

  • short_name (str) –

    The short name either of the group or the job_layer_definition.

  • path (list[str]) –

    The path is a list of string which stores the information of the current tree path. This is used to construct a string for unifying job_layer_definition names by their tree path.

Returns:

Source code in src/qgis_server_light/exporter/extract.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def create_unified_short_name(self, short_name: str, path: list[str]):
    """
    Creates the unified short name, separated by the configured separator.

    Args:
        short_name: The short name either of the group or the job_layer_definition.
        path: The path is a list of string which stores the information of the current
            tree path. This is
            used to construct a string for unifying job_layer_definition names by
            their tree path.

    Returns:

    """
    short_name_parts = path + [short_name]
    return self.unify_layer_names_by_group_separator.join(short_name_parts)
extract_datasource_dict(layer: QgsMapLayer) -> dict

Decodes a QGIS map job_layer_definition datasource into a dict and ensures that types are pythonic and pathes are clean for further usage.

Parameters:

  • layer (QgsMapLayer) –

    The job_layer_definition which the datasource should be extracted from.

Returns:

  • dict –

    The decoded and cleaned datasource.

Source code in src/qgis_server_light/exporter/extract.py
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
def extract_datasource_dict(self, layer: QgsMapLayer) -> dict:
    """
    Decodes a QGIS map job_layer_definition datasource into a dict and ensures that
    types are pythonic and pathes are
    clean for further usage.

    Args:
        layer: The job_layer_definition which the datasource should be extracted from.

    Returns:
        The decoded and cleaned datasource.
    """
    decoded = QgsProviderRegistry.instance().decodeUri(
        layer.providerType(), layer.dataProvider().dataSourceUri()
    )
    logging.debug(f"Layer source: {decoded}")
    for key in decoded:
        if str(decoded[key]) in ("None", "NULL"):
            decoded[key] = None
            continue
        if key == "path":
            # QGIS 3 returns url encoded paths, which leads to incorrect operations,
            # eg: ".%2Fdata%2Fhiroshima.mbtiles" instead of "./data/hiroshima.mbtiles"
            # For QGIS 4 projects, the value is expected to be decoded already.
            if self.version.majorVersion() <= 3:
                decoded_path = unquote(decoded[key])
            else:
                decoded_path = decoded[key]
            # Make path relative to the qgis_project
            decoded[key] = decoded_path.replace(f"{self.qgis_project.readPath('./')}/", "")
        else:
            decoded[key] = str(decoded[key])
    return decoded
extract_group(group: QgsLayerTreeGroup, path: list[str])

Collects data pertaining to a QGIS job_layer_definition tree group. Basically this translates a QgsLayerTreeGroup into a QGIS-Server-Light TreeGroup.

Parameters:

  • group (QgsLayerTreeGroup) –

    The group which is handled.

  • path (list[str]) –

    The path is a list of string which stores the information of the current tree path. This is used to construct a string for unifying job_layer_definition names by their tree path.

Source code in src/qgis_server_light/exporter/extract.py
180
181
182
183
184
185
186
187
188
189
190
191
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
222
223
def extract_group(
    self,
    group: QgsLayerTreeGroup,
    path: list[str],
):
    """
    Collects data pertaining to a QGIS job_layer_definition tree group. Basically
    this translates a QgsLayerTreeGroup
    into a QGIS-Server-Light TreeGroup.

    Args:
        group: The group which is handled.
        path: The path is a list of string which stores the information of the current
            tree path. This is
            used to construct a string for unifying job_layer_definition names by
            their tree path.
    """
    children = []
    for child in group.children():
        if isinstance(child, QgsLayerTreeGroup):
            children.append(
                self.create_unified_short_name(self.get_group_short_name(child), path)
            )
        else:
            children.append(child.layer().id())
    short_name = self.create_unified_short_name(self.get_group_short_name(group), path[:-1])
    self.qsl_tree.members.append(
        TreeGroup(
            id=short_name,
            name=short_name,
            children=children,
            is_checked=group.itemVisibilityChecked(),
            is_expanded=group.isExpanded(),
        )
    )
    self.qsl_datasets.group.append(
        Group(
            id=short_name,
            name=short_name,
            title=self.get_group_title(group),
            is_checked=group.itemVisibilityChecked(),
            is_expanded=group.isExpanded(),
        )
    )
extract_metadata(project: QgsProject) -> MetaData staticmethod

Creates a QSL interface instance for metadate pulled out of the QGIS project.

Parameters:

  • project (QgsProject) –

    The instantiated QGIS project.

Returns:

  • MetaData –

    The metadata interface instance.

Source code in src/qgis_server_light/exporter/extract.py
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
@staticmethod
def extract_metadata(project: QgsProject) -> MetaData:
    """
    Creates a QSL interface instance for metadate pulled out of the QGIS project.

    Args:
        project: The instantiated QGIS project.

    Returns:
        The metadata interface instance.
    """
    _meta = project.metadata()
    wms_entries = Exporter.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=[link.url for link in _meta.links()],
    )
extract_save_layer(child: QgsLayerTreeLayer, path: list[str], types_from_editor_widget: bool = False)

Save the given job_layer_definition to the output path.

Source code in src/qgis_server_light/exporter/extract.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
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
273
274
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
def extract_save_layer(
    self,
    child: QgsLayerTreeLayer,
    path: list[str],
    types_from_editor_widget: bool = False,
):
    """Save the given job_layer_definition to the output path."""
    layer = child.layer()
    is_checked = child.itemVisibilityChecked()
    layer_type = self.get_layer_type(layer)
    if layer_type is None:
        self.qsl_config.warning(
            f"Layer type {layer.type().name} of layer "
            f"{layer.title() or layer.name()!r} is not supported.",
            code=ExportMessage.Code.LAYER_TYPE_UNSUPPORTED,
            layer_id=layer.id(),
        )
        return

    self.rewrite_datasource_with_qgis3_compatible_uri(layer)
    if not self.is_layer_valid(layer):
        error_message = (
            layer.error().summary()
            or layer.dataProvider().error().summary()
            or f"Layer with name {layer.title() or layer.name()!r} is not valid."
        )
        self.qsl_config.error(
            error_message,
            code=ExportMessage.Code.LAYER_INVALID,
            layer_id=layer.id(),
        )
        raise self.build_export_failure()

    decoded = self.extract_datasource_dict(layer)
    short_name = self.short_name(self.get_layer_short_name(child), path)
    if layer.isSpatial():
        crs = self.create_qsl_crs_from_qgs_layer(layer)
        layer_extent = self.get_layer_extent(layer)
        if layer_extent is None:
            self.qsl_config.error(
                "Could not determine an extent for layer",
                code=ExportMessage.Code.LAYER_EXTENT_MISSING,
                layer_id=layer.id(),
            )
            raise self.build_export_failure()
        bbox_wgs84 = self.create_qsl_bbox_from_qgis_rectangle_wgs84(
            self.qgis_project, layer, layer_extent
        )
        bbox = self.create_qsl_bbox_from_qgis_rectangle_extent(layer_extent)
        is_spatial = True
    else:
        crs = None
        bbox_wgs84 = None
        bbox = None
        is_spatial = False

    if layer_type == "vector":
        data_provider: QgsVectorDataProvider = layer.dataProvider()
        if data_provider.isValid() and data_provider.empty():
            self.qsl_config.warning(
                "Vector layer is empty",
                code=ExportMessage.Code.LAYER_EMPTY,
                layer_id=layer.id(),
            )
        if layer.providerType().lower() == "ogr":
            source = DataSource(ogr=self.create_qsl_source_ogr(decoded))
        elif layer.providerType().lower() == "postgres":
            source = DataSource(postgres=self.create_qsl_source_postgresql(decoded))
        elif layer.providerType().lower() == "wfs":
            # TODO: Correctly implement source!
            source = WfsSource()
        else:
            self.qsl_config.warning(
                f"Unknown provider type {layer.providerType().lower()} "
                f"for vector job_layer_definition {layer.title() or layer.name()}",
                code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                layer_id=layer.id(),
            )
            return
        qsl_vector_dataset_fields = self.create_qsl_fields_from_qgis_field(layer)
        self.qsl_datasets.vector.append(
            Vector(
                name=short_name,
                title=layer.title() or layer.name(),
                styles=self.create_style_list(layer),
                driver=layer.providerType(),
                bbox_wgs84=bbox_wgs84,
                fields=qsl_vector_dataset_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,
                is_spatial=is_spatial,
                is_checked=is_checked,
                # Qgis server property WMSBackgroundLayer can only be set for raster layers
                is_background=False,
            )
        )
    elif layer_type == "raster":
        if layer.providerType() == "gdal":
            source = DataSource(gdal=self.create_qsl_source_gdal(decoded))
        elif layer.providerType() == "wms":
            if "tileMatrixSet" in decoded:
                source = DataSource(wmts=self.create_qsl_source_wmts(decoded))
            else:
                if decoded.get("type") == "xyz":
                    source = DataSource(xyz=self.create_qsl_source_xyz(decoded))
                else:
                    source = DataSource(wms=self.create_qsl_source_wms(decoded))
        elif layer.providerType() == "wcs":
            source = DataSource(wcs=self.create_qsl_source_wcs(decoded))
        else:
            self.qsl_config.warning(
                f"Unknown provider type in raster layer: {layer.providerType().lower()}",
                code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                layer_id=layer.id(),
            )
            return

        self.qsl_datasets.raster.append(
            Raster(
                name=short_name,
                title=layer.title() or layer.name(),
                styles=self.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(),
                is_spatial=is_spatial,
                is_checked=is_checked,
                is_background=self.is_wms_background_layer(layer),
            )
        )

    elif layer_type == "custom":
        if layer.providerType().lower() in ["xyzvectortiles", "mbtilesvectortiles"]:
            source = DataSource(vector_tile=self.create_qsl_source_vector_tiles(decoded))
        else:
            # TODO: make this more configurable
            self.qsl_config.warning(
                f"Unknown provider type: {layer.providerType().lower()} "
                f"in layer with short_name {short_name}",
                code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                layer_id=layer.id(),
            )
            return
        self.qsl_datasets.custom.append(
            Custom(
                name=short_name,
                title=layer.title() or layer.name(),
                styles=self.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(),
                is_spatial=is_spatial,
                is_checked=is_checked,
                # Qgis server property WMSBackgroundLayer can only be set for raster layers
                is_background=False,
            )
        )
get_group_short_name(group: QgsLayerTreeGroup) -> str staticmethod
Source code in src/qgis_server_light/exporter/extract.py
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
@staticmethod
def get_group_short_name(group: QgsLayerTreeGroup) -> str:
    if group.customProperty("wmsShortName"):
        return group.customProperty("wmsShortName")
    elif hasattr(group, "groupLayer"):  # noqa: SIM102
        # since QGIS 3.38
        if (
            group.groupLayer()
            and group.groupLayer().serverProperties()
            and group.groupLayer().serverProperties().shortName()
        ):
            return group.groupLayer().serverProperties().shortName()
    short_name = Exporter.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: QgsLayerTreeGroup) -> str staticmethod
Source code in src/qgis_server_light/exporter/extract.py
764
765
766
767
768
769
770
771
772
773
774
775
776
@staticmethod
def get_group_title(group: QgsLayerTreeGroup) -> str:
    if group.customProperty("wmsTitle"):
        return group.customProperty("wmsTitle")
    elif hasattr(group, "groupLayer"):  # noqa: SIM102
        # since QGIS 3.38
        if (
            group.groupLayer()
            and group.groupLayer().serverProperties()
            and group.groupLayer().serverProperties().title()
        ):
            return group.groupLayer().serverProperties().title()
    return group.name()
get_layer_extent(layer: QgsMapLayer) -> QgsReferencedRectangle | None

Layer extent in the layer CRS, else the project fallback reprojected into it.

Source code in src/qgis_server_light/exporter/extract.py
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
def get_layer_extent(self, layer: QgsMapLayer) -> QgsReferencedRectangle | None:
    """Layer extent in the layer CRS, else the project fallback reprojected into it."""
    ext = layer.extent()
    if not ext.isNull() and ext.isFinite():
        return QgsReferencedRectangle(ext, layer.crs())

    project = layer.project()
    fallback = self.get_project_extent(project) if project else None
    if fallback is None:
        return None

    ct = QgsCoordinateTransform(fallback.crs(), layer.crs(), project.transformContext())
    try:
        transformed = ct.transformBoundingBox(fallback)
    except QgsCsException as err:
        self.qsl_config.error(
            "Layer extent could not be determined by the data provider and the "
            f"project fallback extent could not be reprojected from "
            f"{fallback.crs().authid()} to {layer.crs().authid()}: {err}",
            code=ExportMessage.Code.LAYER_EXTENT_REPROJECTION_FAILED,
            layer_id=layer.id(),
        )
        raise self.build_export_failure() from err

    self.qsl_config.warning(
        "Layer extent could not be determined by the data provider "
        "and is derived from the project instead.",
        code=ExportMessage.Code.LAYER_EXTENT_FROM_PROJECT,
        layer_id=layer.id(),
    )
    return QgsReferencedRectangle(transformed, layer.crs())
get_layer_short_name(layer: QgsLayerTreeLayer) -> str staticmethod

This method determines which name is used as the short name of the job_layer_definition.

Parameters:

  • layer (QgsLayerTreeLayer) –

    The job_layer_definition which the short name should be derived from.

Returns:

  • str –

    The short name.

Source code in src/qgis_server_light/exporter/extract.py
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
@staticmethod
def get_layer_short_name(layer: QgsLayerTreeLayer) -> str:
    """
    This method determines which name is used as the short name of the job_layer_definition.

    Args:
        layer: The job_layer_definition which the short name should be derived from.

    Returns:
        The short name.
    """
    if layer.layer().shortName():
        return layer.layer().shortName()
    elif (
        hasattr(layer.layer(), "serverProperties")
        and layer.layer().serverProperties().shortName()
    ):
        return layer.layer().serverProperties().shortName()
    return layer.layer().id()
get_layer_type(layer: QgsMapLayer) -> str | None staticmethod

Gets the type of the given Qgis job_layer_definition as a string if the type is supported. This is to flatten the understanding of layers from qgis into something we can handle.

Parameters:

  • layer (QgsMapLayer) –

    The job_layer_definition to decide the type for.

Returns:

  • str | None –

    "raster", "vector" or "custom" if a job_layer_definition matched and None otherwise.

Source code in src/qgis_server_light/exporter/extract.py
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
@staticmethod
def get_layer_type(layer: QgsMapLayer) -> str | None:
    """
    Gets the type of the given Qgis job_layer_definition as a string if the type is supported.
    This is to flatten the
    understanding of layers from qgis into something we can handle.

    Args:
        layer: The job_layer_definition to decide the type for.

    Returns:
        "raster", "vector" or "custom" if a job_layer_definition matched and None otherwise.
    """
    if isinstance(layer, QgsRasterLayer):
        return "raster"
    elif isinstance(layer, QgsVectorLayer):
        return "vector"
    elif isinstance(
        layer, (QgsVectorTileLayer, QgsTiledSceneLayer, QgsPointCloudLayer, QgsMeshLayer)
    ):
        return "custom"
    return None
get_project_extent(project: QgsProject) -> QgsReferencedRectangle | None staticmethod

WMS advertised extent, else View Settings full extent, else project CRS area of use.

Source code in src/qgis_server_light/exporter/extract.py
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
@staticmethod
def get_project_extent(project: QgsProject) -> QgsReferencedRectangle | None:
    """WMS advertised extent, else View Settings full extent, else project CRS area of use."""
    wms = QgsServerProjectUtils.wmsExtent(project)
    if not wms.isNull():
        return QgsReferencedRectangle(wms, project.crs())

    full = project.viewSettings().fullExtent()
    if not full.isNull():
        return full

    crs_bounds = project.crs().bounds()  # area of use, always in EPSG:4326
    if not crs_bounds.isNull():
        return QgsReferencedRectangle(crs_bounds, QgsCoordinateReferenceSystem("EPSG:4326"))

    return None
get_project_server_entries(project, scope_or_scopes: str | list) -> dict staticmethod

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/extract.py
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
@staticmethod
def get_project_server_entries(project, scope_or_scopes: 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 scope not 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, []))
is_layer_valid(layer: QgsMapLayer) -> bool staticmethod
Source code in src/qgis_server_light/exporter/extract.py
1136
1137
1138
1139
1140
1141
1142
1143
1144
@staticmethod
def is_layer_valid(layer: QgsMapLayer) -> bool:
    if not layer.isValid():
        logging.debug(f"Layer error: {layer.error().summary()}")
        return False
    if not layer.dataProvider().isValid():
        logging.debug(f"Data provider error: {layer.dataProvider().error().summary()}")
        return False
    return True
is_wms_background_layer(layer: QgsMapLayer) -> bool staticmethod
Source code in src/qgis_server_light/exporter/extract.py
760
761
762
@staticmethod
def is_wms_background_layer(layer: QgsMapLayer) -> bool:
    return bool(layer.customProperty("WMSBackgroundLayer", False))
make_wgs84_geom_transform(project, layer) -> QgsCoordinateTransform staticmethod

Creates a QgisCoordinateTransform context to transform a job_layer_definition to EPSG:4326 aka wgs84.

Parameters:

  • project –

    The QGIS project instance.

  • layer –

    The job_layer_definition which's extent should be reprojected.

Returns:

  • QgsCoordinateTransform –

    The QGIS transformation context.

Source code in src/qgis_server_light/exporter/extract.py
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
@staticmethod
def make_wgs84_geom_transform(project, layer) -> QgsCoordinateTransform:
    """
    Creates a QgisCoordinateTransform context to transform a job_layer_definition
    to EPSG:4326 aka wgs84.

    Args:
        project: The QGIS project instance.
        layer: The job_layer_definition which's extent should be reprojected.

    Returns:
        The QGIS transformation context.
    """
    source_crs = layer.crs()
    epsg_4326 = QgsCoordinateReferenceSystem("EPSG:4326")
    return QgsCoordinateTransform(source_crs, epsg_4326, project)
obtain_editor_widget_type_from_qgis_field(field: QgsField) -> tuple[str, str, str, str] | tuple[str, None, None, None] staticmethod

We simply mimikri QGIS Server here

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

Parameters:

  • field (QgsField) –

    The field of an QgsVectorLayer.

Returns:

  • tuple[str, str, str, str] | tuple[str, None, None, None] –

    Unified type name regarding

  • tuple[str, str, str, str] | tuple[str, None, None, None] –
Source code in src/qgis_server_light/exporter/extract.py
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
@staticmethod
def obtain_editor_widget_type_from_qgis_field(
    field: QgsField,
) -> tuple[str, str, str, str] | tuple[str, None, None, 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()
    editor_widget_type = setup.type()
    if editor_widget_type == "DateTime":
        field_format = config.get(
            "field_format", QgsDateTimeFieldFormatter.defaultFormat(attribute_type)
        )
        if field_format == QgsDateTimeFieldFormatter.TIME_FORMAT:
            return editor_widget_type, "time", "string", "time"
        elif field_format == QgsDateTimeFieldFormatter.DATE_FORMAT:
            return editor_widget_type, "date", "string", "date"
        elif (
            field_format == QgsDateTimeFieldFormatter.DATETIME_FORMAT
            or field_format == QgsDateTimeFieldFormatter.QT_ISO_FORMAT
        ):
            return editor_widget_type, "dateTime", "string", "date-time"
    elif editor_widget_type == "Range":
        if config.get("Precision"):
            config_precision = int(config["Precision"])
            if config_precision != field.precision():
                if config_precision == 0:
                    return editor_widget_type, "integer", "integer", "int64"
                else:
                    return editor_widget_type, "decimal", "number", "double"

    return editor_widget_type, None, None, None
obtain_is_generated(provider, field_index: int) -> bool staticmethod
Source code in src/qgis_server_light/exporter/extract.py
715
716
717
718
719
720
721
@staticmethod
def obtain_is_generated(provider, field_index: int) -> bool:
    # the OGR provider (GeoPackage fid, ...) lets GDAL assign the identifier on insert,
    # other providers tell it with a default value, e.g. a sequence
    if provider.name() == "ogr":
        return True
    return bool(provider.defaultValueClause(field_index))
obtain_nullable(field: QgsField) -> bool staticmethod

Parameters:

  • field (QgsField) –

    The field of an QgsVectorLayer.

Returns:

  • bool –

    False if the field carries a NotNull constraint (possibly combined with

  • bool –

    others like Unique or Expression), True otherwise.

Source code in src/qgis_server_light/exporter/extract.py
656
657
658
659
660
661
662
663
664
665
666
667
668
@staticmethod
def obtain_nullable(field: QgsField) -> bool:
    """

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

    Returns:
        False if the field carries a NotNull constraint (possibly combined with
        others like Unique or Expression), True otherwise.
    """
    constraints = field.constraints().constraints()
    return not constraints & QgsFieldConstraints.Constraint.ConstraintNotNull
obtain_simple_types_from_qgis_field_json(field: QgsField) -> tuple[str, str] | tuple[str, None] staticmethod

Delivers the type match for json based on the field QgsField type.

Parameters:

  • field (QgsField) –

    The field of an QgsVectorLayer.

Returns:

  • tuple[str, str] | tuple[str, None] –

    Unified type name and format in a tuple.

Source code in src/qgis_server_light/exporter/extract.py
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
@staticmethod
def obtain_simple_types_from_qgis_field_json(
    field: QgsField,
) -> tuple[str, str] | tuple[str, None]:
    """
    Delivers the type match for json based on the field QgsField type.

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

    Returns:
        Unified type name and format in a tuple.
    """
    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:
        # we handle all unknown types as string. Since its for JavaScript, this should be safe.
        return "string", None
obtain_simple_types_from_qgis_field_xml(field: QgsField) -> str staticmethod

Parameters:

  • field (QgsField) –

    The field of an QgsVectorLayer.

Returns:

  • 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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
@staticmethod
def obtain_simple_types_from_qgis_field_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"
open_qgis_project(path_to_project: str) -> QgsProject staticmethod

Parameters:

  • path_to_project (str) –

    The absolute path on the file system where the project

Returns:

  • QgsProject –

    The opened project (read).

Source code in src/qgis_server_light/exporter/extract.py
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
@staticmethod
def open_qgis_project(path_to_project: str) -> QgsProject:
    """


    Args:
        path_to_project: The absolute path on the file system where the project
        can be read from.

    Returns:
        The opened project (read).
    """
    project = QgsProject.instance()
    project.read(path_to_project)
    return project
prepare_qgis_project_name(project: QgsProject) -> str staticmethod

Parameters:

  • project (QgsProject) –

    The instantiated QGIS project.

Returns:

  • str –

    Project name

Source code in src/qgis_server_light/exporter/extract.py
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
@staticmethod
def prepare_qgis_project_name(project: QgsProject) -> str:
    """


    Args:
        project: The instantiated QGIS project.

    Returns:
        Project name
    """
    return project.title() or project.baseName()
provide_field_length(field: QgsField) -> int | None staticmethod
Source code in src/qgis_server_light/exporter/extract.py
670
671
672
673
674
675
676
@staticmethod
def provide_field_length(field: QgsField) -> int | None:
    length = field.length()
    if length > 0:
        return length
    else:
        return None
provide_field_precision(field: QgsField) -> int | None staticmethod
Source code in src/qgis_server_light/exporter/extract.py
678
679
680
681
682
683
684
@staticmethod
def provide_field_precision(field: QgsField) -> int | None:
    precision = field.precision()
    if precision > 0:
        return precision
    else:
        return None
provide_float(value) -> float | None staticmethod

Just an internal helper

Source code in src/qgis_server_light/exporter/extract.py
606
607
608
609
610
611
@staticmethod
def provide_float(value) -> float | None:
    """Just an internal helper"""
    if value is None:
        return None
    return float(value)
rewrite_datasource_with_qgis3_compatible_uri(layer: QgsMapLayer)
Source code in src/qgis_server_light/exporter/extract.py
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
def rewrite_datasource_with_qgis3_compatible_uri(self, layer: QgsMapLayer):
    # QGIS 3 is inconsistent in how it encodes/decodes source URIs, whereas
    # QGIS 4 systematically percent-encodes reserved characters inside datasource values.
    # A project saved by QGIS >= 4 and read by a QGIS 3 build (QSL is based on
    # QGIS 3) therefore needs an unquote() pass to get clean values.
    if not Qgis.version().startswith("3."):
        return

    if self.version.majorVersion() >= 4:
        registry = QgsProviderRegistry.instance()
        original_uri = layer.source()
        qgis3_compatible_uri = registry.encodeUri(
            layer.providerType(),
            {
                key: unquote(value) if isinstance(value, str) else value
                for (key, value) in registry.decodeUri(
                    layer.providerType(), original_uri
                ).items()
            },
        )
        logging.debug(
            f"Layer {layer.id()} datasource URI from QGIS 4 project is rewritten: "
            f"original={original_uri!r}, QGIS 3 compatible={qgis3_compatible_uri!r}"
        )
        layer.setDataSource(qgis3_compatible_uri)
run() -> Config
Source code in src/qgis_server_light/exporter/extract.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def run(self) -> Config:
    if project_error := self.qgis_project.error():
        self.qsl_config.error(
            project_error,
            code=ExportMessage.Code.PROJECT_READ_FAILED,
        )
        raise self.build_export_failure()
    if self.version.majorVersion() > 4:
        self.qsl_config.error(
            f"QGIS project version {self.version.text()} is not supported.",
            code=ExportMessage.Code.PROJECT_VERSION_UNSUPPORTED,
        )
        raise self.build_export_failure()
    self.walk_qgis_project_tree(self.qgis_project_tree_root, [])
    self.qsl_config.relations = self.create_qsl_relations(self.qgis_project)
    return self.qsl_config
sanitize_name(raw: str, lower: bool = False) -> str staticmethod

Transforms an arbitrary string into a WMS/WFS and URL compatible short name for a job_layer_definition or group.

Steps: 1. Unicode‑NFD → ASCII‑transliteration (removes umlauts/diacritics). 2. All chars, which are NOT [A‑Za‑z0‑9_.‑], will be replaced by '' ersetzen. 3. Reduce multiple underscore '' to a single one. 4. Remove leading '', '.', '-'. 5. If the string is empty OR does not start with a letter OR not start with '', a leading '_' will be added. 6. Optional all will be converted to lowercase (lower=True).

Source code in src/qgis_server_light/exporter/extract.py
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
@staticmethod
def sanitize_name(raw: str, lower: bool = False) -> str:
    """
    Transforms an arbitrary string into a WMS/WFS and URL compatible short name for a
    job_layer_definition or group.

    Steps:
    1. Unicode‑NFD → ASCII‑transliteration (removes umlauts/diacritics).
    2. All chars, which are NOT [A‑Za‑z0‑9_.‑], will be replaced by '_' ersetzen.
    3. Reduce multiple underscore '_' to a single one.
    4. Remove leading '_', '.', '-'.
    5. If the string is empty OR does not start with a letter OR not start with '_',
       a leading '_' will be added.
    6. Optional all will be converted to lowercase (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
short_name(short_name: str, path: list[str]) -> str

Decides if to use the short name itself or the unified version by the tree path.

Parameters:

  • short_name (str) –

    The short name either of the group or the job_layer_definition.

  • path (list[str]) –

    The path is a list of string which stores the information of the current tree path. This is used to construct a string for unifying job_layer_definition names by their tree path.

Returns:

  • str –

    The short name itself or its unified tree path.

Source code in src/qgis_server_light/exporter/extract.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def short_name(self, short_name: str, path: list[str]) -> str:
    """
    Decides if to use the short name itself or the unified version by the tree path.

    Args:
        short_name: The short name either of the group or the job_layer_definition.
        path: The path is a list of string which stores the information of the current
            tree path. This is
            used to construct a string for unifying job_layer_definition names by
            their tree path.

    Returns:
        The short name itself or its unified tree path.
    """
    if self.unify_layer_names_by_group:
        return self.create_unified_short_name(short_name, path)
    else:
        return short_name
sslmode_int_to_str(ssl_mode: int) -> str staticmethod

Mapper to map ssl modes from QGIS int to plain postgres.

Parameters:

  • ssl_mode (int) –

    The ssl mode of the datasource as a int value matching one of https://qgis.org/pyqgis/3.44/core/QgsDataSourceUri.html#qgis.core.QgsDataSourceUri.SslMode

Returns:

  • str –

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

Source code in src/qgis_server_light/exporter/extract.py
957
958
959
960
961
962
963
964
965
966
967
968
969
@staticmethod
def sslmode_int_to_str(ssl_mode: int) -> str:
    """
    Mapper to map ssl modes from QGIS int to plain postgres.

    Args:
        ssl_mode: The ssl mode of the datasource as a int value matching one of
            https://qgis.org/pyqgis/3.44/core/QgsDataSourceUri.html#qgis.core.QgsDataSourceUri.SslMode

    Returns:
        The string representation of the ssl mode as it is used by postgres connections.
    """
    return QgsDataSourceUri.encodeSslMode(int(ssl_mode))
walk_qgis_project_tree(entity: QgsLayerTreeNode, path: list[str])

This is a highly recursive function which walks to the qgis job_layer_definition tree to extract all knowledge out of it. It is called from itself again for each level of group like elements which are found.

Parameters:

  • entity (QgsLayerTreeNode) –

    The QGIS projects tree node which can be a QgsLayerTree, QgsLayerTreeGroup or QgsLayerTreeLayer.

  • path (list[str]) –

    The path is a list of string which stores the information of the current tree path. This is used to construct a string for unifying job_layer_definition names by their tree path.

Source code in src/qgis_server_light/exporter/extract.py
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
174
175
176
177
178
def walk_qgis_project_tree(
    self,
    entity: QgsLayerTreeNode,
    path: list[str],
):
    """
    This is a highly recursive function which walks to the qgis job_layer_definition
    tree to extract all knowledge out
    of it. It is called from itself again for each level of group like elements
    which are found.

    Args:
        entity: The QGIS projects tree node which can be a QgsLayerTree, QgsLayerTreeGroup or
            QgsLayerTreeLayer.
        path: The path is a list of string which stores the information of the current
            tree path. This is
            used to construct a string for unifying job_layer_definition names by their
            tree path.
    """
    if isinstance(entity, QgsLayerTreeLayer):
        # this is a job_layer_definition, we can extract its information
        self.extract_save_layer(
            entity,
            path,
        )
    elif isinstance(entity, (QgsLayerTreeGroup, QgsLayerTree)):
        # these are "group like" elements, we need to step into them one level deeper.
        short_name = self.get_group_short_name(entity)
        if short_name != "":
            # '' is the root of the tree, we don't want it to be part of the path
            path = path + [short_name]
        self.extract_group(
            entity,
            path,
        )
        for child in entity.children():
            # we handle all the children of the group like thing.
            self.walk_qgis_project_tree(
                child,
                path,
            )
    else:
        self.qsl_config.warning(
            "This element was not expected while walking QGIS project tree: "
            f"{type(entity).__name__} at {'/'.join(path)}",
            code=ExportMessage.Code.TREE_NODE_UNSUPPORTED,
        )