-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcore.py
More file actions
572 lines (519 loc) · 23.2 KB
/
core.py
File metadata and controls
572 lines (519 loc) · 23.2 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
"""Item crud client."""
import json
import logging
import operator
from datetime import datetime
from typing import List, Optional, Set, Type, Union
from urllib.parse import unquote_plus, urlencode, urljoin
import attr
import geoalchemy2 as ga
import sqlalchemy as sa
import stac_pydantic
from fastapi import HTTPException
from pydantic import ValidationError
from shapely.geometry import Polygon as ShapelyPolygon
from shapely.geometry import shape
from sqlakeyset import get_page
from sqlalchemy import func
from sqlalchemy.orm import Session as SqlSession
from stac_fastapi.api.models import create_post_request_model
from stac_fastapi.types.config import Settings
from stac_fastapi.types.core import BaseCoreClient
from stac_fastapi.types.errors import NotFoundError
from stac_fastapi.types.search import BaseSearchPostRequest
from stac_fastapi.types.stac import Collection, Collections, Item, ItemCollection
from stac_pydantic.links import Relations
from stac_pydantic.shared import MimeTypes
from stac_fastapi.sqlalchemy import serializers
from stac_fastapi.sqlalchemy.extensions.query import Operator
from stac_fastapi.sqlalchemy.models import database
from stac_fastapi.sqlalchemy.session import Session
from stac_fastapi.sqlalchemy.tokens import PaginationTokenClient
logger = logging.getLogger(__name__)
NumType = Union[float, int]
@attr.s
class CoreCrudClient(PaginationTokenClient, BaseCoreClient):
"""Client for core endpoints defined by stac."""
session: Session = attr.ib(default=attr.Factory(Session.create_from_env))
item_table: Type[database.Item] = attr.ib(default=database.Item)
collection_table: Type[database.Collection] = attr.ib(default=database.Collection)
item_serializer: Type[serializers.Serializer] = attr.ib(
default=serializers.ItemSerializer
)
collection_serializer: Type[serializers.Serializer] = attr.ib(
default=serializers.CollectionSerializer
)
#added attribute post_request_model to the class core crud client
post_request_model: type = attr.ib(factory=lambda: create_post_request_model([]))
@staticmethod
def _lookup_id(
id: str, table: Type[database.BaseModel], session: SqlSession
) -> Type[database.BaseModel]:
"""Lookup row by id."""
row = session.query(table).filter(table.id == id).first()
if not row:
raise NotFoundError(f"{table.__name__} {id} not found")
return row
def all_collections(self, **kwargs) -> Collections:
"""Read all collections from the database."""
base_url = str(kwargs["request"].base_url)
with self.session.reader.context_session() as session:
collections = session.query(self.collection_table).all()
serialized_collections = [
self.collection_serializer.db_to_stac(collection, base_url=base_url)
for collection in collections
]
links = [
{
"rel": Relations.root.value,
"type": MimeTypes.json,
"href": base_url,
},
{
"rel": Relations.parent.value,
"type": MimeTypes.json,
"href": base_url,
},
{
"rel": Relations.self.value,
"type": MimeTypes.json,
"href": urljoin(base_url, "collections"),
},
]
collection_list = Collections(
collections=serialized_collections or [], links=links
)
return collection_list
def get_collection(self, collection_id: str, **kwargs) -> Collection:
"""Get collection by id."""
base_url = str(kwargs["request"].base_url)
with self.session.reader.context_session() as session:
collection = self._lookup_id(collection_id, self.collection_table, session)
return self.collection_serializer.db_to_stac(collection, base_url)
def item_collection(
self,
collection_id: str,
bbox: Optional[List[NumType]] = None,
datetime: Optional[str] = None,
limit: int = 10,
token: str = None,
**kwargs,
) -> ItemCollection:
"""Read an item collection from the database."""
base_url = str(kwargs["request"].base_url)
with self.session.reader.context_session() as session:
# Look up the collection first to get a 404 if it doesn't exist
_ = self._lookup_id(collection_id, self.collection_table, session)
query = (
session.query(self.item_table)
.join(self.collection_table)
.filter(self.collection_table.id == collection_id)
.order_by(self.item_table.datetime.desc(), self.item_table.id)
)
# Spatial query
geom = None
if bbox:
bbox = [float(x) for x in bbox]
if len(bbox) == 4:
geom = ShapelyPolygon.from_bounds(*bbox)
elif len(bbox) == 6:
"""Shapely doesn't support 3d bounding boxes so use the 2d portion"""
bbox_2d = [bbox[0], bbox[1], bbox[3], bbox[4]]
geom = ShapelyPolygon.from_bounds(*bbox_2d)
if geom:
# Ensure `geom` is a Shapely geometry
if not hasattr(geom, "wkt"):
geom = shape(geom)
#convert to WKT
wkt = geom.wkt
"""use shapelys shape method, geoalchemy's shape attribute has been removed"""
filter_geom = func.ST_GeomFromText(wkt, 4326)
#filter_geom = from_shape(geom, srid=4326)
query = query.filter(
ga.func.ST_Intersects(self.item_table.geometry, filter_geom)
)
# Temporal query
if datetime:
# Two tailed query (between)
dts = datetime.split("/")
# Non-interval date ex. "2000-02-02T00:00:00.00Z"
if len(dts) == 1:
query = query.filter(self.item_table.datetime == dts[0])
# is there a benefit to between instead of >= and <= ?
elif dts[0] not in ["", ".."] and dts[1] not in ["", ".."]:
query = query.filter(self.item_table.datetime.between(*dts))
# All items after the start date
elif dts[0] not in ["", ".."]:
query = query.filter(self.item_table.datetime >= dts[0])
# All items before the end date
elif dts[1] not in ["", ".."]:
query = query.filter(self.item_table.datetime <= dts[1])
count = None
if self.extension_is_enabled("ContextExtension"):
count_query = query.statement.with_only_columns(
[func.count()]
).order_by(None)
count = query.session.execute(count_query).scalar()
token = self.get_token(token) if token else token
page = get_page(query, per_page=limit, page=(token or False))
# Create dynamic attributes for each page
page.next = (
self.insert_token(keyset=page.paging.bookmark_next)
if page.paging.has_next
else None
)
page.previous = (
self.insert_token(keyset=page.paging.bookmark_previous)
if page.paging.has_previous
else None
)
links = [
{
"rel": Relations.self.value,
"type": "application/geo+json",
"href": str(kwargs["request"].url),
},
{
"rel": Relations.root.value,
"type": "application/json",
"href": str(kwargs["request"].base_url),
},
{
"rel": Relations.parent.value,
"type": "application/json",
"href": str(kwargs["request"].base_url),
},
]
if page.next:
links.append(
{
"rel": Relations.next.value,
"type": "application/geo+json",
"href": f"{kwargs['request'].base_url}collections/{collection_id}/items?token={page.next}&limit={limit}",
"method": "GET",
}
)
if page.previous:
links.append(
{
"rel": Relations.previous.value,
"type": "application/geo+json",
"href": f"{kwargs['request'].base_url}collections/{collection_id}/items?token={page.previous}&limit={limit}",
"method": "GET",
}
)
response_features = []
for item in page:
response_features.append(
self.item_serializer.db_to_stac(item, base_url=base_url)
)
context_obj = None
if self.extension_is_enabled("ContextExtension"):
context_obj = {
"returned": len(page),
"limit": limit,
"matched": count,
}
return ItemCollection(
type="FeatureCollection",
features=response_features,
links=links,
context=context_obj,
)
def get_item(self, item_id: str, collection_id: str, **kwargs) -> Item:
"""Get item by id."""
base_url = str(kwargs["request"].base_url)
with self.session.reader.context_session() as session:
db_query = session.query(self.item_table)
db_query = db_query.filter(self.item_table.collection_id == collection_id)
db_query = db_query.filter(self.item_table.id == item_id)
item = db_query.first()
if not item:
raise NotFoundError(f"{self.item_table.__name__} {item_id} not found")
return self.item_serializer.db_to_stac(item, base_url=base_url)
def get_search(
self,
collections: Optional[List[str]] = None,
ids: Optional[List[str]] = None,
bbox: Optional[List[NumType]] = None,
datetime: Optional[Union[str, datetime]] = None,
limit: Optional[int] = 10,
query: Optional[str] = None,
token: Optional[str] = None,
fields: Optional[List[str]] = None,
sortby: Optional[str] = None,
intersects: Optional[str] = None,
**kwargs,
) -> ItemCollection:
"""GET search catalog."""
# Parse request parameters
base_args = {
"collections": collections,
"ids": ids,
"bbox": bbox,
"limit": limit,
"token": token,
"fields": fields,
"query": json.loads(unquote_plus(query)) if query else query,
}
#print(f"\n--------------------------------Parsed base_args---------------\n\n{base_args}")
if datetime:
base_args["datetime"] = datetime
if intersects:
base_args["intersects"] = json.loads(unquote_plus(intersects))
if sortby:
# https://github.com/radiantearth/stac-spec/tree/master/api-spec/extensions/sort#http-get-or-post-form
sort_param = []
for sort in sortby:
sort_param.append(
{
"field": sort[1:],
"direction": "asc" if sort[0] == "+" else "desc",
}
)
base_args["sortby"] = sort_param
if fields:
includes = set()
excludes = set()
for field in fields:
if field[0] == "-":
excludes.add(field[1:])
elif field[0] == "+":
includes.add(field[1:])
else:
includes.add(field)
base_args["fields"] = {"include": includes, "exclude": excludes}
#print(f'-----------------------base args: {base_args["fields"]}--------------------------')
# Do the request
try:
search_request = self.post_request_model(**base_args)
#print(f"\n------------------------------Validated search_request------\n\n", search_request)
except ValidationError:
raise HTTPException(status_code=400, detail="Invalid parameters provided")
resp = self.post_search(search_request, request=kwargs["request"])
#print(f'\n------------------search response before pagination links----------------------\n\n{resp}\n\n{type(resp)}')
# Pagination
page_links = []
for link in resp["links"]:
if link["rel"] == Relations.next or link["rel"] == Relations.previous:
query_params = dict(kwargs["request"].query_params)
if link["body"] and link["merge"]:
query_params.update(link["body"])
link["method"] = "GET"
link["href"] = f"{link['href']}?{urlencode(query_params)}"
link["body"] = None
link["merge"] = False
page_links.append(link)
else:
page_links.append(link)
resp["links"] = page_links
return resp
def post_search(
self, search_request: BaseSearchPostRequest, **kwargs
) -> ItemCollection:
"""POST search catalog."""
base_url = str(kwargs["request"].base_url)
with self.session.reader.context_session() as session:
token = (
self.get_token(search_request.token) if search_request.token else False
)
query = session.query(self.item_table)
# Filter by collection
count = None
if search_request.collections:
query = query.join(self.collection_table).filter(
sa.or_(
*[
self.collection_table.id == col_id
for col_id in search_request.collections
]
)
)
# Sort
if search_request.sortby:
sort_fields = [
getattr(
self.item_table.get_field(sort.field),
sort.direction.value,
)()
for sort in search_request.sortby
]
sort_fields.append(self.item_table.id)
query = query.order_by(*sort_fields)
else:
# Default sort is date
query = query.order_by(
self.item_table.datetime.desc(), self.item_table.id
)
# Ignore other parameters if ID is present
if search_request.ids:
id_filter = sa.or_(
*[self.item_table.id == i for i in search_request.ids]
)
items = query.filter(id_filter).order_by(self.item_table.id)
page = get_page(items, per_page=search_request.limit, page=token)
if self.extension_is_enabled("ContextExtension"):
count = len(search_request.ids)
page.next = (
self.insert_token(keyset=page.paging.bookmark_next)
if page.paging.has_next
else None
)
page.previous = (
self.insert_token(keyset=page.paging.bookmark_previous)
if page.paging.has_previous
else None
)
else:
# Spatial query
geom = None
if search_request.intersects is not None:
geom = shape(search_request.intersects)
elif search_request.bbox:
if len(search_request.bbox) == 4:
geom = ShapelyPolygon.from_bounds(*search_request.bbox)
elif len(search_request.bbox) == 6:
"""Shapely doesn't support 3d bounding boxes we'll just use the 2d portion"""
bbox_2d = [
search_request.bbox[0],
search_request.bbox[1],
search_request.bbox[3],
search_request.bbox[4],
]
geom = ShapelyPolygon.from_bounds(*bbox_2d)
# if geom:
# filter_geom = ga.shape(geom, srid=4326)
# query = query.filter(
# ga.func.ST_Intersects(self.item_table.geometry, filter_geom)
# )
"""geoalchemy has removed the shape attribute, we default to shapely"""
if geom:
# Ensure `geom` is a Shapely geometry
if not hasattr(geom, "wkt"):
geom = shape(geom)
# Convert to WKT
wkt = geom.wkt
filter_geom = func.ST_GeomFromText(wkt, 4326)
query = query.filter(
func.ST_Intersects(self.item_table.geometry, filter_geom)
)
# Temporal query
if search_request.datetime:
# Two tailed query (between)
dts = search_request.datetime.split("/")
# Non-interval date ex. "2000-02-02T00:00:00.00Z"
if len(dts) == 1:
query = query.filter(self.item_table.datetime == dts[0])
# is there a benefit to between instead of >= and <= ?
elif dts[0] not in ["", ".."] and dts[1] not in ["", ".."]:
query = query.filter(self.item_table.datetime.between(*dts))
# All items after the start date
elif dts[0] not in ["", ".."]:
query = query.filter(self.item_table.datetime >= dts[0])
# All items before the end date
elif dts[1] not in ["", ".."]:
query = query.filter(self.item_table.datetime <= dts[1])
# Query fields
if search_request.query:
for field_name, expr in search_request.query.items():
field = self.item_table.get_field(field_name)
for op, value in expr.items():
if op == Operator.gte:
query = query.filter(operator.ge(field, value))
elif op == Operator.lte:
query = query.filter(operator.le(field, value))
else:
query = query.filter(op.operator(field, value))
if self.extension_is_enabled("ContextExtension"):
count_query = query.statement.with_only_columns(
[func.count()]
).order_by(None)
count = query.session.execute(count_query).scalar()
page = get_page(query, per_page=search_request.limit, page=token)
# Create dynamic attributes for each page
page.next = (
self.insert_token(keyset=page.paging.bookmark_next)
if page.paging.has_next
else None
)
page.previous = (
self.insert_token(keyset=page.paging.bookmark_previous)
if page.paging.has_previous
else None
)
links = []
if page.next:
links.append(
{
"rel": Relations.next.value,
"type": "application/geo+json",
"href": f"{kwargs['request'].base_url}search",
"method": "POST",
"body": {"token": page.next},
"merge": True,
}
)
if page.previous:
links.append(
{
"rel": Relations.previous.value,
"type": "application/geo+json",
"href": f"{kwargs['request'].base_url}search",
"method": "POST",
"body": {"token": page.previous},
"merge": True,
}
)
response_features = []
filter_kwargs = {}
for item in page:
response_features.append(
self.item_serializer.db_to_stac(item, base_url=base_url)
)
#for i in response_features:
##print(f'----------------response item(db_to_stac) --------------\n\n{i}')
#apply the fields extension logic
if self.extension_is_enabled("FieldsExtension"):
include = getattr(search_request.fields, "include", set()) or set()
exclude = getattr(search_request.fields, "exclude", set()) or set()
#dynamically include query fields
if search_request.query is not None:
query_include: Set[str] = set(
[
k
if k in Settings.get().indexed_fields
else f"properties.{k}"
for k in search_request.query.keys()
]
)
# Only pass if non-empty
if include and len(include) > 0:
response_features = [
json.loads(stac_pydantic.Item(**feat).model_dump_json(include=include))
for feat in response_features
]
#print(f'---------------------------------fields extension response included------------------------\n\n{response_features}')
elif exclude and len(exclude) > 0:
response_features = [
json.loads(stac_pydantic.Item(**feat).model_dump_json(exclude=exclude))
for feat in response_features
]
#print(f'---------------------------------fields extension response excluded------------------------\n\n{response_features}')
else:
response_features = [
json.loads(stac_pydantic.Item(**feat).model_dump_json())
for feat in response_features
]
context_obj = None
if self.extension_is_enabled("ContextExtension"):
context_obj = {
"returned": len(page),
"limit": search_request.limit,
"matched": count,
}
return ItemCollection(
type="FeatureCollection",
features=response_features,
links=links,
context=context_obj,
)