-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathentity.py
370 lines (329 loc) · 12.5 KB
/
entity.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
import logging
from dataclasses import asdict
from typing import Optional, List, Set, Dict, Union
from fastapi import APIRouter, Depends, HTTPException, Request, Path
from pydantic import Required
from pydantic.error_wrappers import ErrorWrapper
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.exceptions import RequestValidationError
from sqlalchemy.orm import Session
from application.core.models import GeoJSON, EntityModel
from application.data_access.digital_land_queries import (
get_datasets,
get_local_authorities,
get_typologies_with_entities,
get_dataset_query,
get_typology_names,
)
from application.data_access.entity_queries import (
get_entity_query,
get_entity_search,
lookup_entity_link,
)
from application.data_access.dataset_queries import get_dataset_names
from application.search.enum import SuffixEntity
from application.search.filters import QueryFilters
from application.core.templates import templates
from application.core.utils import (
DigitalLandJSONResponse,
to_snake,
entity_attribute_sort_key,
make_links,
)
from application.exceptions import (
DatasetValueNotFound,
TypologyValueNotFound,
)
from application.db.session import get_session
router = APIRouter()
logger = logging.getLogger(__name__)
def _get_geojson(data: List[EntityModel]) -> Dict[str, Union[str, List[GeoJSON]]]:
features = []
for entity in data:
if entity.geojson is not None:
geojson = entity.geojson
properties = entity.dict(
exclude={"geojson", "geometry", "point"}, by_alias=True
)
geojson.properties = properties
features.append(geojson)
return {"type": "FeatureCollection", "features": features}
def _get_entity_json(data: List[EntityModel], include: Optional[Set] = None):
entities = []
for entity in data:
if include is not None:
# always return at least the entity (id)
include.add("entity")
e = entity.dict(include=include, by_alias=True)
else:
e = entity.dict(exclude={"geojson"}, by_alias=True)
entities.append(e)
return entities
def get_entity(
request: Request,
entity: int = Path(default=Required, description="Entity id"),
extension: Optional[SuffixEntity] = None,
session: Session = Depends(get_session),
):
e, old_entity_status, new_entity_id = get_entity_query(session, entity)
if old_entity_status == 410:
if extension:
raise HTTPException(
detail=f"Entity {entity} has been removed", status_code=410
)
else:
return templates.TemplateResponse(
"entity-gone.html",
{
"request": request,
"entity": str(entity),
},
status_code=410,
)
elif old_entity_status == 301:
if extension:
return RedirectResponse(
f"/entity/{new_entity_id}.{extension}", status_code=301
)
else:
return RedirectResponse(f"/entity/{new_entity_id}", status_code=301)
elif e is not None:
if extension is not None and extension.value == "json":
return e.dict(by_alias=True, exclude={"geojson"})
if e.geojson is not None:
geojson = e.geojson
properties = e.dict(exclude={"geojson", "geometry", "point"}, by_alias=True)
geojson.properties = properties
else:
geojson = None
if extension is not None and extension.value == "geojson":
if geojson is not None:
return geojson
else:
raise HTTPException(
status_code=406, detail="geojson for entity not available"
)
e_dict = e.dict(by_alias=True, exclude={"geojson"})
e_dict_sorted = {
key: e_dict[key]
for key in sorted(e_dict.keys(), key=entity_attribute_sort_key)
}
if geojson is not None:
geojson_dict = dict(geojson)
else:
geojson_dict = None
# need to remove any dependency on facts this should be changed when fields added to postgis
fields = None
# get field specifications and convert to dictionary to easily access
# fields = get_field_specifications(e_dict_sorted.keys())
# if fields:
# fields = [field.dict(by_alias=True) for field in fields]
# fields = {field["field"]: field for field in fields}
# get dictionary of fields which have linked datasets
dataset_fields = get_datasets(session, datasets=e_dict_sorted.keys())
dataset_fields = [
dataset_field.dict(by_alias=True) for dataset_field in dataset_fields
]
dataset_fields = [dataset_field["dataset"] for dataset_field in dataset_fields]
dataset = get_dataset_query(session, e.dataset)
organisation_entity, _, _ = get_entity_query(session, e.organisation_entity)
entityLinkFields = [
"article-4-direction",
"permitted-development-rights",
"tree-preservation-order",
]
linked_entities = {}
# for each entityLinkField, if that key exists in the entity dict, then
# lookup the entity and add it to the linked_entities dict
for field in entityLinkFields:
if field in e_dict_sorted:
linked_entity = lookup_entity_link(
session, e_dict_sorted[field], field, e_dict_sorted["dataset"]
)
if linked_entity is not None:
linked_entities[field] = linked_entity
return templates.TemplateResponse(
"entity.html",
{
"request": request,
"row": e_dict_sorted,
"linked_entities": linked_entities,
"entity": e,
"pipeline_name": e.dataset,
"references": [],
"breadcrumb": [],
"schema": None,
"typology": e.typology,
"entity_prefix": "",
"geojson_features": e.geojson if e.geojson is not None else None,
"geojson": geojson_dict,
"fields": fields,
"dataset_fields": dataset_fields,
"dataset": dataset,
"organisation_entity": organisation_entity,
},
)
else:
raise HTTPException(status_code=404, detail="entity not found")
def validate_dataset(dataset: str, datasets: list):
"""
Given a dataset and a set of datasets will check if dataset is a valid one
if not it will raise the appropriate error. Query not included to reduce
number of queries on the server.
"""
if not dataset:
return dataset
missing_datasets = set(dataset).difference(set(datasets))
if missing_datasets:
raise RequestValidationError(
errors=[
ErrorWrapper(
DatasetValueNotFound(
f"Requested datasets do not exist: {','.join(missing_datasets)}. "
f"Valid dataset names: {','.join(datasets)}",
dataset_names=datasets,
),
loc=("dataset"),
)
]
)
return
def validate_typologies(typologies, typology_names):
if not typologies:
return typologies
missing_typologies = set(typologies).difference(set(typology_names))
if missing_typologies:
raise RequestValidationError(
errors=[
ErrorWrapper(
TypologyValueNotFound(
f"Requested datasets do not exist: {','.join(missing_typologies)}. "
f"Valid dataset names: {','.join(typology_names)}",
dataset_names=typology_names,
),
loc=("typology"),
)
]
)
return
def search_entities(
request: Request,
query_filters: QueryFilters = Depends(),
extension: Optional[SuffixEntity] = None,
session: Session = Depends(get_session),
):
# get query_filters as a dict
query_params = asdict(query_filters)
# TODO minimse queries by using normal queries below rather than returning the names
# queries required for additional validations
dataset_names = get_dataset_names(session)
typology_names = get_typology_names(session)
# additional validations
validate_dataset(query_params.get("dataset", None), dataset_names)
validate_typologies(query_params.get("typology", None), typology_names)
# Run entity query
data = get_entity_search(session, query_params)
# the query does some normalisation to remove empty
# params and they get returned from search
params = data["params"]
scheme = request.url.scheme
netloc = request.url.netloc
path = request.url.path
query = request.url.query
links = make_links(scheme, netloc, path, query, data)
if extension is not None and extension.value == "json":
if params.get("field") is not None:
include = set([to_snake(field) for field in params.get("field")])
entities = _get_entity_json(data["entities"], include=include)
else:
entities = _get_entity_json(data["entities"])
return {"entities": entities, "links": links, "count": data["count"]}
if extension is not None and extension.value == "geojson":
geojson = _get_geojson(data["entities"])
geojson["links"] = links
return geojson
typologies = get_typologies_with_entities(session)
typologies = [t.dict() for t in typologies]
# dataset facet
response = get_datasets(session)
columns = ["dataset", "name", "plural", "typology", "themes", "paint_options"]
datasets = [dataset.dict(include=set(columns)) for dataset in response]
local_authorities = get_local_authorities(session, "local-authority-eng")
local_authorities = [la.dict() for la in local_authorities]
if links.get("prev") is not None:
prev_url = links["prev"]
else:
prev_url = None
if links.get("next") is not None:
next_url = links["next"]
else:
next_url = None
# default is HTML
has_geographies = any((e.typology == "geography" for e in data["entities"]))
return templates.TemplateResponse(
"search.html",
{
"request": request,
"count": data["count"],
"limit": params["limit"],
"data": data["entities"],
"datasets": datasets,
"local_authorities": local_authorities,
"typologies": typologies,
"query": {"params": params},
"active_filters": [
filter_name
for filter_name, values in params.items()
if filter_name != "limit" and values is not None
],
"url_query_params": {
"str": ("&").join(
[
"{}={}".format(param[0], param[1])
for param in request.query_params._list
]
),
"list": request.query_params._list,
},
"next_url": next_url,
"prev_url": prev_url,
"has_geographies": has_geographies,
},
)
# Route ordering in important. Match routes with extensions first
router.add_api_route(
".{extension}",
endpoint=search_entities,
response_class=DigitalLandJSONResponse,
tags=["Search entity"],
summary="This endpoint searches for a subset of entities from all entities filtered by specified parameters returning the entity set in the format specified.", # noqa: E501
)
router.add_api_route(
"/",
endpoint=search_entities,
responses={
200: {
"content": {
"application/x-qgis-project": {},
"application/geo+json": {},
"text/json": {},
},
"description": "List of entities in one of a number of different formats.",
}
},
response_class=HTMLResponse,
include_in_schema=False,
)
router.add_api_route(
"/{entity}.{extension}",
get_entity,
response_class=DigitalLandJSONResponse,
tags=["Get entity"],
summary="This endpoint returns data on one specific entity matching the specified ID in the format requested.",
)
router.add_api_route(
"/{entity}",
endpoint=get_entity,
response_class=HTMLResponse,
include_in_schema=False,
)