forked from geopython/pycsw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecords.py
More file actions
1547 lines (1290 loc) · 56.9 KB
/
records.py
File metadata and controls
1547 lines (1290 loc) · 56.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
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
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
# Angelos Tzotsos <tzotsos@gmail.com>
#
# Copyright (c) 2025 Tom Kralidis
# Copyright (c) 2021 Angelos Tzotsos
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================
import json
import logging
from operator import itemgetter
import os
from urllib.parse import urlencode, quote
from owslib.ogcapi.records import Records
from pygeofilter.parsers.ecql import parse as parse_ecql
from pygeofilter.parsers.cql2_json import parse as parse_cql2_json
from pycsw import __version__
from pycsw.core import log
from pycsw.core.config import StaticContext
from pycsw.core.metadata import parse_record
from pycsw.core.pygeofilter_evaluate import to_filter
from pycsw.core.util import bind_url, get_today_and_now, jsonify_links, load_custom_repo_mappings, str2bool, wkt2geom
from pycsw.ogc.api.oapi import gen_oapi
from pycsw.ogc.api.util import match_env_var, render_j2_template, to_json, to_rfc3339
LOGGER = logging.getLogger(__name__)
#: Return headers for requests (e.g:X-Powered-By)
HEADERS = {
'Content-Type': 'application/json',
'X-Powered-By': f'pycsw {__version__}'
}
THISDIR = os.path.dirname(os.path.realpath(__file__))
CONFORMANCE_CLASSES = [
'http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/core',
'http://www.opengis.net/spec/ogcapi-common-2/1.0/conf/collections',
'http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/core',
'http://www.opengis.net/spec/ogcapi-features-3/1.0/conf/queryables',
'http://www.opengis.net/spec/ogcapi-features-3/1.0/conf/queryables-query-parameters', # noqa
'http://www.opengis.net/spec/ogcapi-features-3/1.0/conf/filter',
'http://www.opengis.net/spec/ogcapi-features-3/1.0/conf/features-filter',
'http://www.opengis.net/spec/ogcapi-features-4/1.0/conf/create-replace-delete', # noqa
'http://www.opengis.net/spec/ogcapi-records-1/1.0/conf/core',
'http://www.opengis.net/spec/ogcapi-records-1/1.0/conf/sorting',
'http://www.opengis.net/spec/ogcapi-records-1/1.0/conf/json',
'http://www.opengis.net/spec/ogcapi-records-1/1.0/conf/html',
'http://www.opengis.net/spec/cql2/1.0/conf/cql2-json',
'http://www.opengis.net/spec/cql2/1.0/conf/cql2-text'
]
class API:
"""API object"""
def __init__(self, config: dict):
"""
constructor
:param config: pycsw configuration dict
:returns: `pycsw.ogc.api.API` instance
"""
self.mode = 'ogcapi-records'
self.config = config
log.setup_logger(self.config.get('logging', {}))
if self.config['server']['url'].startswith('${'):
LOGGER.debug(f"Server URL is an environment variable: {self.config['server']['url']}")
url_ = match_env_var(self.config['server']['url'])
else:
url_ = self.config['server']['url']
LOGGER.debug(f'Server URL: {url_}')
self.config['server']['url'] = url_.rstrip('/')
self.facets = self.config['repository'].get('facets', ['type'])
self.context = StaticContext()
LOGGER.debug('Setting limit')
try:
self.limit = int(self.config['server']['maxrecords'])
except KeyError:
self.limit = 10
LOGGER.debug(f'limit: {self.limit}')
repo_filter = self.config['repository'].get('filter')
custom_mappings_path = self.config['repository'].get('mappings')
if custom_mappings_path is not None:
md_core_model = load_custom_repo_mappings(custom_mappings_path)
if md_core_model is not None:
self.context.md_core_model = md_core_model
else:
LOGGER.exception(
'Could not load custom mappings: %s', custom_mappings_path)
self.orm = 'sqlalchemy'
from pycsw.core import repository
try:
LOGGER.info('Loading default repository')
self.repository = repository.Repository(
self.config['repository']['database'],
self.context,
table=self.config['repository']['table'],
repo_filter=repo_filter
)
LOGGER.debug(f'Repository loaded {self.repository.dbtype}')
except Exception as err:
msg = f'Could not load repository {err}'
LOGGER.exception(msg)
raise
def get_content_type(self, headers, args):
"""
Decipher content type requested
:param headers: `dict` of HTTP request headers
:param args: `dict` of query arguments
:returns: `str` of response content type
"""
content_type = 'application/json'
format_ = args.get('f')
if headers and 'Accept' in headers:
if 'text/html' in headers['Accept']:
content_type = 'text/html'
elif 'application/xml' in headers['Accept']:
content_type = 'application/xml'
if format_ is not None:
if format_ == 'json':
content_type = 'application/json'
elif format_ == 'xml':
content_type = 'application/xml'
elif format_ == 'html':
content_type = 'text/html'
return content_type
def get_response(self, status, headers, data, template=None):
"""
Provide response
:param status: `int` of HTTP status
:param headers: `dict` of HTTP request headers
:param data: `dict` of response data
:param template: template filename (default is `None`)
:returns: tuple of headers, status code, content
"""
if headers.get('Content-Type') == 'text/html' and template is not None:
content = render_j2_template(self.config, template, data)
else:
pretty_print = str2bool(self.config['server'].get('pretty_print', False))
content = to_json(data, pretty_print)
headers['Content-Length'] = len(content)
return headers, status, content
def landing_page(self, headers_, args):
"""
Provide API landing page
:param headers_: copy of HEADERS object
:param args: request parameters
:returns: tuple of headers, status code, content
"""
headers_['Content-Type'] = self.get_content_type(headers_, args)
response = {
'id': 'pycsw-catalogue',
'links': [],
'title': self.config['metadata']['identification']['title'],
'description':
self.config['metadata']['identification']['description'],
'keywords':
self.config['metadata']['identification']['keywords']
}
LOGGER.debug('Creating links')
response['links'] = [{
'rel': 'self',
'type': 'application/json',
'title': 'This document as JSON',
'href': f"{self.config['server']['url']}?f=json",
'hreflang': self.config['server']['language']
}, {
'rel': 'conformance',
'type': 'application/json',
'title': 'Conformance as JSON',
'href': f"{self.config['server']['url']}/conformance?f=json"
}, {
'rel': 'service-doc',
'type': 'text/html',
'title': 'The OpenAPI definition as HTML',
'href': f"{self.config['server']['url']}/openapi?f=html"
}, {
'rel': 'service-desc',
'type': 'application/vnd.oai.openapi+json;version=3.0',
'title': 'The OpenAPI definition as JSON',
'href': f"{self.config['server']['url']}/openapi?f=json"
}, {
'rel': 'data',
'type': 'application/json',
'title': 'Collections as JSON',
'href': f"{self.config['server']['url']}/collections?f=json"
}, {
'rel': 'search',
'type': 'application/json',
'title': 'Search collections',
'href': f"{self.config['server']['url']}/search"
}, {
'rel': 'child',
'type': 'application/json',
'title': 'Main metadata collection',
'href': f"{self.config['server']['url']}/collections/metadata:main?f=json"
}, {
'rel': 'service',
'type': 'application/xml',
'title': 'CSW 3.0.0 endpoint',
'href': f"{self.config['server']['url']}/csw"
}, {
'rel': 'service',
'type': 'application/xml',
'title': 'CSW 2.0.2 endpoint',
'href': f"{self.config['server']['url']}/csw?service=CSW&version=2.0.2&request=GetCapabilities"
}, {
'rel': 'service',
'type': 'application/xml',
'title': 'OpenSearch endpoint',
'href': f"{self.config['server']['url']}/opensearch"
}, {
'rel': 'service',
'type': 'application/xml',
'title': 'OAI-PMH endpoint',
'href': f"{self.config['server']['url']}/oaipmh"
}, {
'rel': 'service',
'type': 'application/xml',
'title': 'SRU endpoint',
'href': f"{self.config['server']['url']}/sru"
}, {
'rel': 'http://www.opengis.net/def/rel/ogc/1.0/queryables',
'type': 'application/schema+json',
'title': 'Queryables',
'href': f"{self.config['server']['url']}/queryables"
}, {
'rel': 'child',
'type': 'application/json',
'title': 'Main collection',
'href': f"{self.config['server']['url']}/collections/metadata:main"
},{
'rel': 'http://www.opengis.net/def/rel/ogc/1.0/ogc-catalog',
'type': 'application/json',
'title': 'Record catalogue collection',
'href': f"{self.config['server']['url']}/collections/metadata:main"
}
]
return self.get_response(200, headers_, response, 'landing_page.html')
def openapi(self, headers_, args):
"""
Provide OpenAPI document / Swagger
:param headers_: copy of HEADERS object
:param args: request parameters
:returns: tuple of headers, status code, content
"""
headers_['Content-Type'] = self.get_content_type(headers_, args)
if headers_['Content-Type'] == 'application/json':
headers_['Content-Type'] = 'application/vnd.oai.openapi+json;version=3.0'
filepath = f"{THISDIR}/../../core/schemas/ogc/ogcapi/records/part1/1.0/ogcapi-records-1.yaml"
response = gen_oapi(self.config, filepath)
return self.get_response(200, headers_, response, 'openapi.html')
def conformance(self, headers_, args):
"""
Provide API conformance
:param headers_: copy of HEADERS object
:param args: request parameters
:returns: tuple of headers, status code, content
"""
headers_['Content-Type'] = self.get_content_type(headers_, args)
response = {
'conformsTo': CONFORMANCE_CLASSES
}
return self.get_response(200, headers_, response, 'conformance.html')
def collections(self, headers_, args):
"""
Provide API collections
:param headers_: copy of HEADERS object
:param args: request parameters
:returns: tuple of headers, status code, content
"""
headers_['Content-Type'] = self.get_content_type(headers_, args)
collections = []
LOGGER.debug('Generating default metadata:main collection')
collection_info = self.get_collection_info()
collections.append(collection_info)
LOGGER.debug('Generating virtual collections')
virtual_collections = self.repository.query_collections()
for virtual_collection in virtual_collections:
virtual_collection_info = self.get_collection_info(
virtual_collection.identifier,
dict(title=virtual_collection.title,
description=virtual_collection.abstract))
collections.append(virtual_collection_info)
response = {
'collections': collections
}
url_base = f"{self.config['server']['url']}/collections"
is_html = headers_['Content-Type'] == 'text/html'
response['links'] = [{
'rel': 'self' if not is_html else 'alternate',
'type': 'application/json',
'title': 'This document as JSON',
'href': f"{url_base}?f=json",
'hreflang': self.config['server']['language']
}, {
'rel': 'self' if is_html else 'alternate',
'type': 'text/html',
'title': 'This document as HTML',
'href': f"{url_base}?f=html",
'hreflang': self.config['server']['language']
}]
return self.get_response(200, headers_, response, 'collections.html')
def collection(self, headers_, args, collection='metadata:main'):
"""
Provide API collections
:param headers_: copy of HEADERS object
:param args: request parameters
:param collection: collection name
:returns: tuple of headers, status code, content
"""
headers_['Content-Type'] = self.get_content_type(headers_, args)
LOGGER.debug(f'Generating {collection} collection')
if collection == 'metadata:main':
collection_info = self.get_collection_info()
else:
virtual_collection = self.repository.query_ids([collection])[0]
collection_info = self.get_collection_info(
virtual_collection.identifier,
dict(title=virtual_collection.title,
description=virtual_collection.abstract))
response = collection_info
url_base = f"{self.config['server']['url']}/collections/{collection}"
is_html = headers_['Content-Type'] == 'text/html'
response['links'] = [{
'rel': 'self' if not is_html else 'alternate',
'type': 'application/json',
'title': 'This document as JSON',
'href': f"{url_base}?f=json",
'hreflang': self.config['server']['language']
}, {
'rel': 'self' if is_html else 'alternate',
'type': 'text/html',
'title': 'This document as HTML',
'href': f"{url_base}?f=html",
'hreflang': self.config['server']['language']
}, {
'rel': 'items',
'type': 'application/geo+json',
'title': 'items as GeoJSON',
'href': f"{url_base}/items?f=json",
'hreflang': self.config['server']['language']
}, {
'rel': 'items',
'type': 'text/html',
'title': 'items as HTML',
'href': f"{url_base}/items?f=html",
'hreflang': self.config['server']['language']
}, {
'rel': 'http://www.opengis.net/def/rel/ogc/1.0/queryables',
'type': 'application/schema+json',
'title': 'Queryables as JSON',
'href': f"{url_base}/queryables?f=json",
'hreflang': self.config['server']['language']
}, {
'rel': 'http://www.opengis.net/def/rel/ogc/1.0/queryables',
'type': 'text/html',
'title': 'Queryables as HTML',
'href': f"{url_base}/queryables?f=html",
'hreflang': self.config['server']['language']
}]
return self.get_response(200, headers_, response, 'collection.html')
def queryables(self, headers_, args, collection='metadata:main'):
"""
Provide collection queryables
:param headers_: copy of HEADERS object
:param args: request parameters
:param collection: name of collection
:returns: tuple of headers, status code, content
"""
headers_['Content-Type'] = self.get_content_type(headers_, args)
if 'json' in headers_['Content-Type']:
headers_['Content-Type'] = 'application/schema+json'
if collection not in self.get_all_collections():
msg = 'Invalid collection'
LOGGER.exception(msg)
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
properties = self.repository.describe()
properties2 = {}
for key, value in properties.items():
if key in self.repository.query_mappings or key == 'geometry':
properties2[key] = value
if collection == 'metadata:main':
title = self.config['metadata']['identification']['title']
else:
title = self.config['metadata']['identification']['title']
virtual_collection = self.repository.query_ids([collection])[0]
title = virtual_collection.title
response = {
'id': collection,
'type': 'object',
'title': title,
'properties': properties2,
'$schema': 'http://json-schema.org/draft/2019-09/schema',
'$id': f"{self.config['server']['url']}/collections/{collection}/queryables"
}
return self.get_response(200, headers_, response, 'queryables.html')
def items(self, headers_, json_post_data, args, collection='metadata:main'):
"""
Provide collection items
:param headers_: copy of HEADERS object
:param args: request parameters
:param collection: collection name
:returns: tuple of headers, status code, content
"""
LOGGER.debug(f'Request args: {args.keys()}')
LOGGER.debug('converting request argument names to lower case')
args = {k.lower(): v for k, v in args.items()}
LOGGER.debug(f'Request args (lower case): {args.keys()}')
headers_['Content-Type'] = self.get_content_type(headers_, args)
reserved_query_params = [
'distributed',
'f',
'facets',
'filter',
'filter-lang',
'limit',
'sortby',
'offset'
]
filter_langs = [
'cql2-json',
'cql2-text'
]
response = {
'type': 'FeatureCollection',
'facets': [],
'features': [],
'links': []
}
cql_query = None
query_parser = None
sortby = None
limit = None
bbox = []
facets_requested = False
collections = []
if collection not in self.get_all_collections():
msg = 'Invalid collection'
LOGGER.exception(msg)
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
if json_post_data is not None:
LOGGER.debug(f'JSON POST data: {json_post_data}')
LOGGER.debug('Transforming JSON POST data into request args')
for p in ['limit', 'bbox', 'datetime', 'collections']:
if p in json_post_data:
if p == 'bbox':
args[p] = ','.join(map(str, json_post_data.get(p)))
else:
args[p] = json_post_data.get(p)
if 'sortby' in json_post_data:
LOGGER.debug('Detected sortby')
args['sortby'] = json_post_data['sortby'][0]['field']
if json_post_data['sortby'][0].get('direction', 'asc') == 'desc':
args['sortby'] = f"-{args['sortby']}"
LOGGER.debug(f'Transformed args: {args}')
if 'filter' in args:
LOGGER.debug(f'CQL query specified {args["filter"]}')
cql_query = args['filter']
filter_lang = args.get('filter-lang')
if filter_lang is not None and filter_lang not in filter_langs:
msg = f'Invalid filter-lang, available: {", ".join(filter_langs)}'
LOGGER.exception(f'{msg} Used: {filter_lang}')
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
LOGGER.debug('Transforming property filters into CQL')
query_args = []
for k, v in args.items():
if k in reserved_query_params:
continue
if k not in reserved_query_params:
if k == 'ids':
ids = ','.join(f'"{x}"' for x in v.split(','))
query_args.append(f"identifier IN ({ids})")
elif k == 'collections':
if isinstance(v, str):
collections = ','.join(f'"{x}"' for x in v.split(','))
else:
collections = ','.join(f'"{x}"' for x in v)
query_args.append(f"parentidentifier IN ({collections})")
elif k == 'anytext':
query_args.append(build_anytext(k, v))
elif k == 'bbox':
query_args.append(f'BBOX(geometry, {v})')
elif k == 'keywords':
query_args.append(f"keywords ILIKE '%{v}%'")
elif k == 'datetime':
if '/' not in v:
query_args.append(f'date = "{v}"')
else:
begin, end = v.split('/')
if begin != '..':
query_args.append(f'time_begin >= "{begin}"')
if end != '..':
query_args.append(f'time_end <= "{end}"')
elif k == 'q':
if v not in [None, '']:
query_args.append(build_anytext('anytext', v))
else:
query_args.append(f'{k} = "{v}"')
facets_requested = str2bool(args.get('facets', False))
if collection != 'metadata:main':
LOGGER.debug('Adding virtual collection filter')
query_args.append(f'parentidentifier = "{collection}"')
LOGGER.debug('Evaluating CQL and other specified filtering parameters')
if cql_query is not None and query_args:
LOGGER.debug('Combining CQL and other specified filtering parameters')
cql_query += ' AND ' + ' AND '.join(query_args)
elif cql_query is not None and not query_args:
LOGGER.debug('Just CQL detected')
elif cql_query is None and query_args:
LOGGER.debug('Just other specified filtering parameters detected')
cql_query = ' AND '.join(query_args)
LOGGER.debug(f'CQL query: {cql_query}')
if cql_query is not None:
LOGGER.debug('Detected CQL text')
query_parser = parse_ecql
elif json_post_data is not None:
if 'limit' in json_post_data:
limit = json_post_data.pop('limit')
if 'sortby' in json_post_data:
sortby = json_post_data.pop('sortby')
if 'collections' in json_post_data:
collections = json_post_data.pop('collections')
if 'bbox' in json_post_data:
bbox = json_post_data.pop('bbox')
if not json_post_data:
LOGGER.debug('No CQL specified, only query parameters')
json_post_data = {}
if not json_post_data and collections and collections != ['metadata:main']:
json_post_data = {'op': 'eq', 'args': [{'property': 'parentidentifier'}, collections[0]]}
if bbox:
json_post_data = {
'op': 'and',
'args': [{
'op': 's_intersects',
'args': [
{'property': 'geometry2'},
{'bbox': [bbox]}
]},
json_post_data
]
}
cql_query = json_post_data
LOGGER.debug('Detected CQL JSON; ignoring all other query predicates')
query_parser = parse_cql2_json
LOGGER.debug(f'query parser: {query_parser}')
if query_parser is not None and json_post_data != {}:
LOGGER.debug('Parsing CQL into AST')
LOGGER.debug(json_post_data)
LOGGER.debug(cql_query)
try:
ast = query_parser(cql_query)
LOGGER.debug(f'Abstract syntax tree: {ast}')
except Exception as err:
msg = f'CQL parsing error: {str(err)}'
LOGGER.exception(msg)
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
LOGGER.debug('Transforming AST into filters')
try:
filters = to_filter(ast, self.repository.dbtype, self.repository.query_mappings)
LOGGER.debug(f'Filter: {filters}')
except Exception as err:
msg = f'CQL evaluator error: {str(err)}'
LOGGER.exception(msg)
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
query = self.repository.session.query(self.repository.dataset).filter(filters)
if facets_requested:
LOGGER.debug('Running facet query')
facets_results = self.get_facets(filters)
else:
query = self.repository.session.query(self.repository.dataset)
facets_results = self.get_facets()
if facets_requested:
response['facets'] = facets_results
else:
response.pop('facets')
if 'sortby' in args:
LOGGER.debug('sortby specified')
sortby = args['sortby']
if sortby is not None:
LOGGER.debug('processing sortby')
if sortby.startswith('-'):
sortby = sortby.lstrip('-')
if sortby not in list(self.repository.query_mappings.keys()):
msg = 'Invalid sortby property'
LOGGER.exception(msg)
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
if args['sortby'].startswith('-'):
query = query.order_by(self.repository.query_mappings[sortby].desc())
else:
query = query.order_by(self.repository.query_mappings[sortby])
if limit is None and 'limit' in args:
limit = int(args['limit'])
LOGGER.debug('limit specified')
if limit < 1:
msg = 'Limit must be a positive integer'
LOGGER.exception(msg)
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
if limit > self.limit:
limit = self.limit
else:
limit = self.limit
offset = int(args.get('offset', 0))
LOGGER.debug(f'Query: {query}')
LOGGER.debug('Querying repository')
count = query.count()
records = query.limit(limit).offset(offset).all()
returned = len(records)
response['numberMatched'] = count
response['numberReturned'] = returned
for record in records:
response['features'].append(record2json(record, self.config['server']['url'], collection, self.mode))
response['distributedFeatures'] = []
distributed = str2bool(args.get('distributed', False))
if distributed:
for fc in self.config.get('federatedcatalogues', []):
LOGGER.debug(f'Running distributed search against {fc}')
fc_url, _, fc_collection = fc.rsplit('/', 2)
try:
w = Records(fc_url)
fc_results = w.collection_items(fc_collection, **args)
for feature in fc_results['features']:
response['distributedFeatures'].append(feature)
except Exception as err:
LOGGER.warning(err)
LOGGER.debug('Creating links')
link_args = {**args}
link_args.pop('f', None)
fragment = f'collections/{collection}/items'
if link_args:
url_base = f"{self.config['server']['url']}/{fragment}?{urlencode(link_args)}"
else:
url_base = f"{self.config['server']['url']}/{fragment}"
is_html = headers_['Content-Type'] == 'text/html'
response['links'].extend([{
'rel': 'self' if not is_html else 'alternate',
'type': 'application/geo+json',
'title': 'This document as GeoJSON',
'href': f"{bind_url(url_base)}f=json",
'hreflang': self.config['server']['language']
}, {
'rel': 'self' if is_html else 'alternate',
'type': 'text/html',
'title': 'This document as HTML',
'href': f"{bind_url(url_base)}f=html",
'hreflang': self.config['server']['language']
}, {
'rel': 'collection',
'type': 'application/json',
'title': 'Collection URL',
'href': f"{self.config['server']['url']}/collections/{collection}",
'hreflang': self.config['server']['language']
}])
if offset > 0:
link_args.pop('offset', None)
prev = max(0, offset - limit)
url_ = f"{self.config['server']['url']}/{fragment}?{urlencode(link_args)}"
response['links'].append(
{
'type': 'application/geo+json',
'rel': 'prev',
'title': 'items (prev)',
'href': f"{bind_url(url_)}offset={prev}",
'hreflang': self.config['server']['language']
})
if (offset + returned) < count:
link_args.pop('offset', None)
next_ = offset + returned
url_ = f"{self.config['server']['url']}/{fragment}?{urlencode(link_args)}"
response['links'].append({
'rel': 'next',
'type': 'application/geo+json',
'title': 'items (next)',
'href': f"{bind_url(url_)}offset={next_}",
'hreflang': self.config['server']['language']
})
if headers_['Content-Type'] == 'text/html':
response['title'] = self.config['metadata']['identification']['title']
response['collection'] = collection
template = 'items.html'
return self.get_response(200, headers_, response, template)
def item(self, headers_, args, collection, item):
"""
Provide collection item
:param headers_: copy of HEADERS object
:param args: request parameters
:param collection: name of collection
:param item: record identifier
:returns: tuple of headers, status code, content
"""
record = None
headers_['Content-Type'] = self.get_content_type(headers_, args)
if collection not in self.get_all_collections():
msg = 'Invalid collection'
LOGGER.exception(msg)
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
LOGGER.debug(f'Querying repository for item {item}')
try:
record = self.repository.query_ids([item])[0]
response = record2json(record, self.config['server']['url'],
collection, self.mode)
except IndexError:
distributed = str2bool(args.get('distributed', False))
if distributed:
for fc in self.config.get('federatedcatalogues', []):
LOGGER.debug(f'Running distributed item search against {fc}')
fc_url, _, fc_collection = fc.rsplit('/', 2)
try:
w = Records(fc_url)
response = record = w.collection_item(fc_collection, item)
LOGGER.debug(f'Found item from {fc}')
break
except RuntimeError:
continue
if record is None:
return self.get_exception(
404, headers_, 'InvalidParameterValue', 'item not found')
if headers_['Content-Type'] == 'application/xml':
return headers_, 200, record.xml
if headers_['Content-Type'] == 'text/html':
response['title'] = self.config['metadata']['identification']['title']
response['collection'] = collection
response['schema-org'] = record2json(
record, self.config['server']['url'], collection, 'schema-org')
if 'json' in headers_['Content-Type']:
headers_['Content-Type'] = 'application/geo+json'
return self.get_response(200, headers_, response, 'item.html')
def manage_collection_item(self, headers_, action='create', item=None, data=None):
"""
:param action: action (create, update, delete)
:param item: record identifier
:param data: raw data / payload
:returns: tuple of headers, status code, content
"""
if not self.config['manager']['transactions']:
return self.get_exception(
405, headers_, 'InvalidParameterValue',
'transactions not allowed')
if action in ['create', 'update'] and data is None:
msg = 'No data found'
LOGGER.error(msg)
return self.get_exception(
400, headers_, 'InvalidParameterValue', msg)
if action in ['create', 'update']:
try:
record = parse_record(self.context, data, self.repository)[0]
except Exception as err:
msg = f'Failed to parse data: {err}'
LOGGER.exception(msg)
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
if not hasattr(record, 'identifier'):
msg = 'Record requires an identifier'
LOGGER.exception(msg)
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
if action == 'create':
LOGGER.debug('Creating new record')
LOGGER.debug(f'Querying repository for item {item}')
try:
_ = self.repository.query_ids([record.identifier])[0]
return self.get_exception(
400, headers_, 'InvalidParameterValue', 'item exists')
except Exception:
LOGGER.debug('Identifier does not exist')
# insert new record
try:
self.repository.insert(record, 'local', get_today_and_now())
except Exception as err:
msg = f'Record creation failed: {err}'
LOGGER.exception(msg)
return self.get_exception(400, headers_, 'InvalidParameterValue', msg)
code = 201
response = {}
elif action == 'update':
LOGGER.debug(f'Querying repository for item {item}')
try:
_ = self.repository.query_ids([record.identifier])[0]
except Exception:
msg = 'Identifier does not exist'
LOGGER.debug(msg)
return self.get_exception(404, headers_, 'InvalidParameterValue', msg)
_ = self.repository.update(record)
code = 204
response = {}
elif action == 'delete':
constraint = {
'where': 'identifier = \'%s\'' % item,
'values': [item]
}
_ = self.repository.delete(constraint)
code = 200
response = {}
return self.get_response(code, headers_, response)
def get_exception(self, status, headers, code, description):
"""
Provide exception report
:param status: `int` of HTTP status code
:param headers_: copy of HEADERS object
:param code: exception code
:param description: exception description
:returns: tuple of headers, status code, content
"""
exception = {