-
Notifications
You must be signed in to change notification settings - Fork 19
/
factory.py
1968 lines (1807 loc) · 72.2 KB
/
factory.py
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
"""tipg.factory: router factories."""
import abc
import csv
import re
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Generator, Iterable, List, Literal, Optional
from urllib.parse import urlencode
import jinja2
import orjson
from morecantile import Tile, TileMatrixSet
from morecantile import tms as default_tms
from morecantile.defaults import TileMatrixSets
from pygeofilter.ast import AstType
from typing_extensions import Annotated
from tipg import model
from tipg.collections import Collection, CollectionList
from tipg.dependencies import (
CollectionParams,
CollectionsParams,
ItemsOutputType,
OutputType,
QueryablesOutputType,
TileParams,
bbox_query,
datetime_query,
filter_query,
function_parameters_query,
ids_query,
properties_filter_query,
properties_query,
sortby_query,
)
from tipg.errors import MissingGeometryColumn, NoPrimaryKey, NotFound
from tipg.resources.enums import MediaType
from tipg.resources.response import GeoJSONResponse, SchemaJSONResponse, orjsonDumps
from tipg.settings import FeaturesSettings, MVTSettings, TMSSettings
from fastapi import APIRouter, Depends, Path, Query
from fastapi.responses import ORJSONResponse
from starlette.datastructures import QueryParams
from starlette.requests import Request
from starlette.responses import HTMLResponse, Response, StreamingResponse
from starlette.routing import compile_path, replace_params
from starlette.templating import Jinja2Templates, _TemplateResponse
tms_settings = TMSSettings()
mvt_settings = MVTSettings()
features_settings = FeaturesSettings()
jinja2_env = jinja2.Environment(
loader=jinja2.ChoiceLoader([jinja2.PackageLoader(__package__, "templates")])
)
DEFAULT_TEMPLATES = Jinja2Templates(env=jinja2_env)
COMMON_CONFORMS = [
"http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/core",
"http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/landingPage",
"http://www.opengis.net/spec/ogcapi-common-2/1.0/conf/collections",
"http://www.opengis.net/spec/ogcapi-common-2/1.0/conf/simple-query",
"http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/json",
"http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/html",
"http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/oas30",
]
FEATURES_CONFORMS = [
"http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/core",
"http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/html",
"http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/oas30",
"http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/geojson",
"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",
]
TILES_CONFORMS = [
"http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/core",
"http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/oas30",
"http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/mvt",
"http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/tileset",
"http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/tilesets-list",
]
def create_csv_rows(data: Iterable[Dict]) -> Generator[str, None, None]:
"""Creates an iterator that returns lines of csv from an iterable of dicts."""
class DummyWriter:
"""Dummy writer that implements write for use with csv.writer."""
def write(self, line: str):
"""Return line."""
return line
# Get the first row and construct the column names
row = next(data) # type: ignore
fieldnames = row.keys()
writer = csv.DictWriter(DummyWriter(), fieldnames=fieldnames)
# Write header
yield writer.writerow(dict(zip(fieldnames, fieldnames)))
# Write first row
yield writer.writerow(row)
# Write all remaining rows
for row in data:
yield writer.writerow(row)
def create_html_response(
request: Request,
data: Any,
templates: Jinja2Templates,
template_name: str,
title: Optional[str] = None,
router_prefix: Optional[str] = None,
**kwargs: Any,
) -> _TemplateResponse:
"""Create Template response."""
urlpath = request.url.path
if root_path := request.app.root_path:
urlpath = re.sub(r"^" + root_path, "", urlpath)
if router_prefix:
urlpath = re.sub(r"^" + router_prefix, "", urlpath)
crumbs = []
baseurl = str(request.base_url).rstrip("/")
if router_prefix:
baseurl += router_prefix
crumbpath = str(baseurl)
if urlpath == "/":
urlpath = ""
for crumb in urlpath.split("/"):
crumbpath = crumbpath.rstrip("/")
part = crumb
if part is None or part == "":
part = "Home"
crumbpath += f"/{crumb}"
crumbs.append({"url": crumbpath.rstrip("/"), "part": part.capitalize()})
return templates.TemplateResponse(
request,
name=f"{template_name}.html",
context={
"response": data,
"template": {
"api_root": baseurl,
"params": request.query_params,
"title": title or template_name,
},
"crumbs": crumbs,
"url": baseurl + urlpath,
"params": str(request.url.query),
**kwargs,
},
)
# ref: https://github.com/python/mypy/issues/5374
@dataclass # type: ignore
class EndpointsFactory(metaclass=abc.ABCMeta):
"""Endpoints Factory."""
# FastAPI router
router: APIRouter = field(default_factory=APIRouter)
# collection dependency
collection_dependency: Callable[..., Collection] = CollectionParams
# Router Prefix is needed to find the path for routes when prefixed
# e.g if you mount the route with `/foo` prefix, set router_prefix to foo
router_prefix: str = ""
templates: Jinja2Templates = DEFAULT_TEMPLATES
# Full application with Landing and Conformance
with_common: bool = True
title: str = "OGC API"
def __post_init__(self):
"""Post Init: register route and configure specific options."""
if self.with_common:
self._landing_route()
self._conformance_route()
self.register_routes()
def url_for(self, request: Request, name: str, **path_params: Any) -> str:
"""Return full url (with prefix) for a specific handler."""
url_path = self.router.url_path_for(name, **path_params)
base_url = str(request.base_url)
if self.router_prefix:
prefix = self.router_prefix.lstrip("/")
# If we have prefix with custom path param we check and replace them with
# the path params provided
if "{" in prefix:
_, path_format, param_convertors = compile_path(prefix)
prefix, _ = replace_params(
path_format, param_convertors, request.path_params.copy()
)
base_url += prefix
return str(url_path.make_absolute_url(base_url=base_url))
def _create_html_response(
self,
request: Request,
data: Any,
template_name: str,
title: Optional[str] = None,
**kwargs: Any,
) -> _TemplateResponse:
return create_html_response(
request,
data,
templates=self.templates,
template_name=template_name,
title=title,
router_prefix=self.router_prefix,
**kwargs,
)
@abc.abstractmethod
def register_routes(self):
"""Register factory Routes."""
...
@property
@abc.abstractmethod
def conforms_to(self) -> List[str]:
"""Endpoints conformances."""
...
@abc.abstractmethod
def links(self, request: Request) -> List[model.Link]:
"""Register factory Routes."""
...
def _conformance_route(self):
"""Register Conformance (/conformance) route."""
@self.router.get(
"/conformance",
response_model=model.Conformance,
response_model_exclude_none=True,
response_class=ORJSONResponse,
responses={
200: {
"content": {
MediaType.json.value: {},
MediaType.html.value: {},
}
},
},
tags=["OGC Common"],
)
def conformance(
request: Request,
output_type: Annotated[Optional[MediaType], Depends(OutputType)] = None,
):
"""Get conformance."""
data = model.Conformance(conformsTo=[*COMMON_CONFORMS, *self.conforms_to])
if output_type == MediaType.html:
return self._create_html_response(
request,
data.model_dump(exclude_none=True, mode="json"),
template_name="conformance",
)
return data
def _landing_route(self):
"""Register Landing (/) and Conformance (/conformance) routes."""
@self.router.get(
"/",
response_model=model.Landing,
response_model_exclude_none=True,
response_class=ORJSONResponse,
responses={
200: {
"content": {
MediaType.json.value: {},
MediaType.html.value: {},
}
},
},
tags=["OGC Common"],
)
def landing(
request: Request,
output_type: Annotated[Optional[MediaType], Depends(OutputType)] = None,
):
"""Get landing page."""
data = model.Landing(
title=self.title,
links=[
model.Link(
title="Landing Page",
href=self.url_for(request, "landing"),
type=MediaType.json,
rel="self",
),
model.Link(
title="the API definition (JSON)",
href=str(request.url_for("openapi")),
type=MediaType.openapi30_json,
rel="service-desc",
),
model.Link(
title="the API documentation",
href=str(request.url_for("swagger_ui_html")),
type=MediaType.html,
rel="service-doc",
),
model.Link(
title="Conformance",
href=self.url_for(request, "conformance"),
type=MediaType.json,
rel="conformance",
),
*self.links(request),
],
)
if output_type == MediaType.html:
return self._create_html_response(
request,
data.model_dump(exclude_none=True, mode="json"),
template_name="landing",
title=self.title,
)
return data
@dataclass
class OGCFeaturesFactory(EndpointsFactory):
"""OGC Features Endpoints Factory."""
# collections dependency
collections_dependency: Callable[..., CollectionList] = CollectionsParams
@property
def conforms_to(self) -> List[str]:
"""Factory conformances."""
return FEATURES_CONFORMS
def links(self, request: Request) -> List[model.Link]:
"""OGC Features API links."""
return [
model.Link(
title="List of Collections",
href=self.url_for(request, "collections"),
type=MediaType.json,
rel="data",
),
model.Link(
title="Collection metadata (Template URL)",
href=self.url_for(
request,
"collection",
collectionId="{collectionId}",
),
type=MediaType.json,
rel="data",
templated=True,
),
model.Link(
title="Collection queryables (Template URL)",
href=self.url_for(
request,
"queryables",
collectionId="{collectionId}",
),
type=MediaType.schemajson,
rel="queryables",
templated=True,
),
model.Link(
title="Collection Features (Template URL)",
href=self.url_for(request, "items", collectionId="{collectionId}"),
type=MediaType.geojson,
rel="data",
templated=True,
),
model.Link(
title="Collection Feature (Template URL)",
href=self.url_for(
request,
"item",
collectionId="{collectionId}",
itemId="{itemId}",
),
type=MediaType.geojson,
rel="data",
templated=True,
),
]
def register_routes(self):
"""Register OGC Features endpoints."""
self._collections_route()
self._collection_route()
self._queryables_route()
self._items_route()
self._item_route()
def _collections_route(self): # noqa: C901
@self.router.get(
"/collections",
response_model=model.Collections,
response_model_exclude_none=True,
response_class=ORJSONResponse,
responses={
200: {
"content": {
MediaType.json.value: {},
MediaType.html.value: {},
}
},
},
tags=["OGC Features API"],
)
def collections(
request: Request,
collection_list: Annotated[
CollectionList,
Depends(self.collections_dependency),
],
output_type: Annotated[
Optional[MediaType],
Depends(OutputType),
] = None,
):
"""List of collections."""
links: list = [
model.Link(
href=self.url_for(request, "collections"),
rel="self",
type=MediaType.json,
),
]
if next_token := collection_list["next"]:
query_params = QueryParams(
{**request.query_params, "offset": next_token}
)
url = self.url_for(request, "collections") + f"?{query_params}"
links.append(
model.Link(
href=url,
rel="next",
type=MediaType.json,
title="Next page",
),
)
if collection_list["prev"] is not None:
prev_token = collection_list["prev"]
qp = dict(request.query_params)
qp.pop("offset", None)
query_params = QueryParams({**qp, "offset": prev_token})
url = self.url_for(request, "collections")
if query_params:
url += f"?{query_params}"
links.append(
model.Link(
href=url,
rel="prev",
type=MediaType.json,
title="Previous page",
),
)
data = model.Collections(
links=links,
numberMatched=collection_list["matched"],
numberReturned=len(collection_list["collections"]),
collections=[
model.Collection(
id=collection.id,
title=collection.id,
description=collection.description,
extent=collection.extent,
links=[
model.Link(
href=self.url_for(
request,
"collection",
collectionId=collection.id,
),
rel="collection",
type=MediaType.json,
),
model.Link(
href=self.url_for(
request,
"items",
collectionId=collection.id,
),
rel="items",
type=MediaType.geojson,
),
model.Link(
href=self.url_for(
request,
"queryables",
collectionId=collection.id,
),
rel="queryables",
type=MediaType.schemajson,
),
],
)
for collection in collection_list["collections"]
],
)
if output_type == MediaType.html:
return self._create_html_response(
request,
data.model_dump(exclude_none=True, mode="json"),
template_name="collections",
title="Collections list",
)
return data
def _collection_route(self):
@self.router.get(
"/collections/{collectionId}",
response_model=model.Collection,
response_model_exclude_none=True,
response_class=ORJSONResponse,
responses={
200: {
"content": {
MediaType.json.value: {},
MediaType.html.value: {},
}
},
},
tags=["OGC Features API"],
)
def collection(
request: Request,
collection: Annotated[Collection, Depends(self.collection_dependency)],
output_type: Annotated[Optional[MediaType], Depends(OutputType)] = None,
):
"""Metadata for a feature collection."""
data = model.Collection.model_validate(
{
**collection.model_dump(),
"title": collection.id,
"extent": collection.extent,
"links": [
{
"href": self.url_for(
request,
"collection",
collectionId=collection.id,
),
"rel": "self",
"type": "application/json",
},
{
"title": "Items",
"href": self.url_for(
request, "items", collectionId=collection.id
),
"rel": "items",
"type": "application/geo+json",
},
{
"title": "Items (CSV)",
"href": self.url_for(
request, "items", collectionId=collection.id
)
+ "?f=csv",
"rel": "alternate",
"type": "text/csv",
},
{
"title": "Items (GeoJSONSeq)",
"href": self.url_for(
request, "items", collectionId=collection.id
)
+ "?f=geojsonseq",
"rel": "alternate",
"type": "application/geo+json-seq",
},
{
"title": "Queryables",
"href": self.url_for(
request,
"queryables",
collectionId=collection.id,
),
"rel": "queryables",
"type": "application/schema+json",
},
],
}
)
if output_type == MediaType.html:
return self._create_html_response(
request,
data.model_dump(exclude_none=True, mode="json"),
template_name="collection",
title=f"{collection.id} collection",
)
return data
def _queryables_route(self):
@self.router.get(
"/collections/{collectionId}/queryables",
response_model=model.Queryables,
response_model_exclude_none=True,
response_model_by_alias=True,
response_class=SchemaJSONResponse,
responses={
200: {
"content": {
MediaType.schemajson.value: {},
MediaType.html.value: {},
}
},
},
tags=["OGC Features API"],
)
def queryables(
request: Request,
collection: Annotated[Collection, Depends(self.collection_dependency)],
output_type: Annotated[
Optional[MediaType], Depends(QueryablesOutputType)
] = None,
):
"""Queryables for a feature collection.
ref: http://docs.ogc.org/DRAFTS/19-079r1.html#filter-queryables
"""
qs = "?" + str(request.query_params) if request.query_params else ""
self_url = self.url_for(request, "queryables", collectionId=collection.id)
data = model.Queryables(
title=collection.id,
link=self_url + qs,
properties=collection.queryables,
)
if output_type == MediaType.html:
return self._create_html_response(
request,
data.model_dump(exclude_none=True, mode="json"),
template_name="queryables",
title=f"{collection.id} queryables",
)
return data
def _items_route(self): # noqa: C901
@self.router.get(
"/collections/{collectionId}/items",
response_class=GeoJSONResponse,
responses={
200: {
"content": {
MediaType.geojson.value: {},
MediaType.html.value: {},
MediaType.csv.value: {},
MediaType.json.value: {},
MediaType.geojsonseq.value: {},
MediaType.ndjson.value: {},
},
"model": model.Items,
},
},
tags=["OGC Features API"],
)
async def items( # noqa: C901
request: Request,
collection: Annotated[Collection, Depends(self.collection_dependency)],
ids_filter: Annotated[Optional[List[str]], Depends(ids_query)],
bbox_filter: Annotated[Optional[List[float]], Depends(bbox_query)],
datetime_filter: Annotated[Optional[List[str]], Depends(datetime_query)],
properties: Annotated[Optional[List[str]], Depends(properties_query)],
cql_filter: Annotated[Optional[AstType], Depends(filter_query)],
sortby: Annotated[Optional[str], Depends(sortby_query)],
geom_column: Annotated[
Optional[str],
Query(
description="Select geometry column.",
alias="geom-column",
),
] = None,
datetime_column: Annotated[
Optional[str],
Query(
description="Select datetime column.",
alias="datetime-column",
),
] = None,
limit: Annotated[
int,
Query(
ge=0,
le=features_settings.max_features_per_query,
description="Limits the number of features in the response.",
),
] = features_settings.default_features_limit,
offset: Annotated[
Optional[int],
Query(
ge=0,
description="Starts the response at an offset.",
),
] = None,
bbox_only: Annotated[
Optional[bool],
Query(
description="Only return the bounding box of the feature.",
alias="bbox-only",
),
] = None,
simplify: Annotated[
Optional[float],
Query(
description="Simplify the output geometry to given threshold in decimal degrees.",
),
] = None,
output_type: Annotated[
Optional[MediaType], Depends(ItemsOutputType)
] = None,
):
output_type = output_type or MediaType.geojson
geom_as_wkt = output_type not in [
MediaType.geojson,
MediaType.geojsonseq,
MediaType.html,
]
item_list = await collection.features(
request.app.state.pool,
ids_filter=ids_filter,
bbox_filter=bbox_filter,
datetime_filter=datetime_filter,
properties_filter=properties_filter_query(request, collection),
function_parameters=function_parameters_query(request, collection),
cql_filter=cql_filter,
sortby=sortby,
properties=properties,
limit=limit,
offset=offset,
geom=geom_column,
dt=datetime_column,
bbox_only=bbox_only,
simplify=simplify,
geom_as_wkt=geom_as_wkt,
)
if output_type in (
MediaType.csv,
MediaType.json,
MediaType.ndjson,
):
if any(
[f.get("geometry", None) is not None for f in item_list["items"]]
):
rows = (
{
"collectionId": collection.id,
"itemId": f.get("id"),
**f.get("properties", {}),
"geometry": f.get("geometry", None),
}
for f in item_list["items"]
)
else:
rows = (
{
"collectionId": collection.id,
"itemId": f.get("id"),
**f.get("properties", {}),
}
for f in item_list["items"]
)
# CSV Response
if output_type == MediaType.csv:
return StreamingResponse(
create_csv_rows(rows),
media_type=MediaType.csv,
headers={
"Content-Disposition": "attachment;filename=items.csv"
},
)
# JSON Response
if output_type == MediaType.json:
return ORJSONResponse(list(rows))
# NDJSON Response
if output_type == MediaType.ndjson:
return StreamingResponse(
(orjsonDumps(row) + b"\n" for row in rows),
media_type=MediaType.ndjson,
headers={
"Content-Disposition": "attachment;filename=items.ndjson"
},
)
qs = "?" + str(request.query_params) if request.query_params else ""
links: List[Dict] = [
{
"title": "Collection",
"href": self.url_for(
request, "collection", collectionId=collection.id
),
"rel": "collection",
"type": "application/json",
},
{
"title": "Items",
"href": self.url_for(request, "items", collectionId=collection.id)
+ qs,
"rel": "self",
"type": "application/geo+json",
},
]
if next_token := item_list["next"]:
query_params = QueryParams(
{**request.query_params, "offset": next_token}
)
url = (
self.url_for(request, "items", collectionId=collection.id)
+ f"?{query_params}"
)
links.append(
{
"href": url,
"rel": "next",
"type": "application/geo+json",
"title": "Next page",
},
)
if item_list["prev"] is not None:
prev_token = item_list["prev"]
qp = dict(request.query_params)
qp.pop("offset")
query_params = QueryParams({**qp, "offset": prev_token})
url = self.url_for(request, "items", collectionId=collection.id)
if query_params:
url += f"?{query_params}"
links.append(
{
"href": url,
"rel": "prev",
"type": "application/geo+json",
"title": "Previous page",
},
)
data = {
"type": "FeatureCollection",
"id": collection.id,
"title": collection.title or collection.id,
"description": collection.description
or collection.title
or collection.id,
"numberMatched": item_list["matched"],
"numberReturned": len(item_list["items"]),
"links": links,
"features": [
{
**feature, # type: ignore
"links": [
{
"title": "Collection",
"href": self.url_for(
request,
"collection",
collectionId=collection.id,
),
"rel": "collection",
"type": "application/json",
},
{
"title": "Item",
"href": self.url_for(
request,
"item",
collectionId=collection.id,
itemId=feature.get("id"),
),
"rel": "item",
"type": "application/geo+json",
},
],
}
for feature in item_list["items"]
],
}
# HTML Response
if output_type == MediaType.html:
return self._create_html_response(
request,
orjson.loads(orjsonDumps(data).decode()),
template_name="items",
title=f"{collection.id} items",
)
# GeoJSONSeq Response
elif output_type == MediaType.geojsonseq:
return StreamingResponse(
(orjsonDumps(f) + b"\n" for f in data["features"]), # type: ignore
media_type=MediaType.geojsonseq,
headers={
"Content-Disposition": "attachment;filename=items.geojson"
},
)
# Default to GeoJSON Response
return GeoJSONResponse(data)
def _item_route(self):
@self.router.get(
"/collections/{collectionId}/items/{itemId}",
response_class=GeoJSONResponse,
responses={
200: {
"content": {
MediaType.geojson.value: {},
MediaType.html.value: {},
MediaType.csv.value: {},
MediaType.json.value: {},
MediaType.geojsonseq.value: {},
MediaType.ndjson.value: {},
},
"model": model.Item,
},
},
tags=["OGC Features API"],
)
async def item(
request: Request,
collection: Annotated[Collection, Depends(self.collection_dependency)],
itemId: Annotated[str, Path(description="Item identifier")],
bbox_only: Annotated[
Optional[bool],
Query(
description="Only return the bounding box of the feature.",
alias="bbox-only",
),
] = None,
simplify: Annotated[
Optional[float],
Query(
description="Simplify the output geometry to given threshold in decimal degrees.",
),
] = None,
geom_column: Annotated[
Optional[str],
Query(
description="Select geometry column.",
alias="geom-column",
),
] = None,
datetime_column: Annotated[
Optional[str],
Query(
description="Select datetime column.",
alias="datetime-column",
),
] = None,
properties: Optional[List[str]] = Depends(properties_query),
output_type: Annotated[
Optional[MediaType], Depends(ItemsOutputType)
] = None,
):
if collection.id_column is None:
raise NoPrimaryKey("No primary key is set on this table")
output_type = output_type or MediaType.geojson