-
Notifications
You must be signed in to change notification settings - Fork 102
/
routes.py
1108 lines (943 loc) · 36.8 KB
/
routes.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
import json
import datetime
import time
from collections import OrderedDict
from warnings import warn
from flask import (
Blueprint,
request,
Response,
current_app,
send_from_directory,
render_template,
jsonify,
g,
)
from werkzeug.exceptions import Forbidden, NotFound, BadRequest, Conflict
from sqlalchemy import distinct, func, desc, asc, select, text, update
from sqlalchemy.orm import joinedload, contains_eager, lazyload, selectinload
from geojson import FeatureCollection, Feature
import sqlalchemy as sa
from utils_flask_sqla.generic import serializeQuery, GenericTable
from utils_flask_sqla.response import to_csv_resp, to_json_resp, json_resp
from utils_flask_sqla_geo.generic import GenericTableGeo
from geonature.utils import filemanager
from geonature.utils.env import DB
from geonature.utils.errors import GeonatureApiError
from geonature.utils.utilsgeometrytools import export_as_geo_file
from geonature.core.gn_meta.models import TDatasets
from geonature.core.gn_synthese.models import (
BibReportsTypes,
Synthese,
TSources,
DefaultsNomenclaturesValue,
VSyntheseForWebApp,
VColorAreaTaxon,
TReport,
)
from geonature.core.gn_synthese.synthese_config import MANDATORY_COLUMNS
from geonature.core.taxonomie.models import (
Taxref,
TaxrefProtectionArticles,
TaxrefProtectionEspeces,
VMTaxrefListForautocomplete,
)
from geonature.core.gn_synthese.utils.query_select_sqla import SyntheseQuery
from geonature.core.gn_permissions import decorators as permissions
from geonature.core.gn_permissions.tools import (
cruved_scope_for_user_in_module,
get_scopes_by_action,
)
from ref_geo.models import LAreas, BibAreasTypes
from pypnusershub.db.tools import user_from_token
from pypnusershub.db.models import User
routes = Blueprint("gn_synthese", __name__)
############################################
########### GET OBSERVATIONS ##############
############################################
@routes.route("/for_web", methods=["GET", "POST"])
@permissions.check_cruved_scope("R", True, module_code="SYNTHESE")
def get_observations_for_web(info_role):
"""Optimized route to serve data for the frontend with all filters.
.. :quickref: Synthese; Get filtered observations
Query filtered by any filter, returning all the fields of the
view v_synthese_for_export::
properties = {
"id": r["id_synthese"],
"date_min": str(r["date_min"]),
"cd_nom": r["cd_nom"],
"nom_vern_or_lb_nom": r["nom_vern"] if r["nom_vern"] else r["lb_nom"],
"lb_nom": r["lb_nom"],
"dataset_name": r["dataset_name"],
"observers": r["observers"],
"url_source": r["url_source"],
"unique_id_sinp": r["unique_id_sinp"],
"entity_source_pk_value": r["entity_source_pk_value"],
}
geojson = json.loads(r["st_asgeojson"])
geojson["properties"] = properties
:param str info_role: Role used to get the associated filters, **TBC**
:qparam str limit: Limit number of synthese returned. Defaults to NB_MAX_OBS_MAP.
:qparam str cd_ref: Filter by TAXREF cd_ref attribute
:qparam str taxonomy_group2_inpn: Filter by TAXREF group2_inpn attribute
:qparam str taxonomy_id_hab: Filter by TAXREF id_habitat attribute
:qparam str taxonomy_lr: Filter by TAXREF cd_ref attribute
:qparam str taxhub_attribut*: Generig TAXREF filter, given attribute & value
:qparam str observers: Filter on observer
:qparam str id_organism: Filter on organism
:qparam str date_min: Start date
:qparam str date_max: End date
:qparam str id_acquisition_framework: *tbd*
:qparam str geoIntersection: Intersect with the geom send from the map
:qparam str period_start: *tbd*
:qparam str period_end: *tbd*
:qparam str area*: Generic filter on area
:qparam str *: Generic filter, given by colname & value
:>jsonarr array data: Array of synthese with geojson key, see above
:>jsonarr int nb_total: Number of observations
:>jsonarr bool nb_obs_limited: Is number of observations capped
"""
if request.is_json:
filters = request.json
elif request.data:
# decode byte to str - compat python 3.5
filters = json.loads(request.data.decode("utf-8"))
else:
filters = {key: request.args.get(key) for key, value in request.args.items()}
if "limit" in filters:
result_limit = filters.pop("limit")
else:
result_limit = current_app.config["SYNTHESE"]["NB_MAX_OBS_MAP"]
query = (
select(
[
VSyntheseForWebApp.id_synthese,
VSyntheseForWebApp.date_min,
VSyntheseForWebApp.lb_nom,
VSyntheseForWebApp.cd_nom,
VSyntheseForWebApp.nom_vern,
VSyntheseForWebApp.count_min,
VSyntheseForWebApp.count_max,
VSyntheseForWebApp.st_asgeojson,
VSyntheseForWebApp.observers,
VSyntheseForWebApp.dataset_name,
VSyntheseForWebApp.url_source,
VSyntheseForWebApp.entity_source_pk_value,
VSyntheseForWebApp.unique_id_sinp,
]
)
.where(VSyntheseForWebApp.the_geom_4326.isnot(None))
.order_by(VSyntheseForWebApp.date_min.desc())
)
synthese_query_class = SyntheseQuery(VSyntheseForWebApp, query, filters)
synthese_query_class.filter_query_all_filters(info_role)
result = DB.session.execute(synthese_query_class.query.limit(result_limit))
geojson_features = []
for r in result:
properties = {
"id": r["id_synthese"],
"date_min": str(r["date_min"]),
"cd_nom": r["cd_nom"],
"nom_vern_or_lb_nom": r["nom_vern"] if r["nom_vern"] else r["lb_nom"],
"lb_nom": r["lb_nom"],
"count_min_max": "{} - {}".format(r["count_min"], r["count_max"])
if r["count_min"] != r["count_max"]
else str(r["count_min"] or ""),
"dataset_name": r["dataset_name"],
"observers": r["observers"],
"url_source": r["url_source"],
"unique_id_sinp": str(r["unique_id_sinp"]),
"entity_source_pk_value": r["entity_source_pk_value"],
}
geometry = json.loads(r["st_asgeojson"])
geojson_features.append(
Feature(
geometry=geometry,
properties=properties,
)
)
return jsonify(FeatureCollection(geojson_features))
@routes.route("", methods=["GET"])
@permissions.check_cruved_scope("R", True, module_code="SYNTHESE")
@json_resp
def get_synthese(info_role):
"""Return synthese row(s) filtered by form params. NOT USED ANY MORE FOR PERFORMANCE ISSUES
.. :quickref: Synthese; Deprecated
.. deprecated:: 2?
Use :route: /for_web instead
Params must have same synthese fields names
:parameter str info_role: Role used to get the associated filters
:returns dict[dict, int, bool]: See description above
"""
# change all args in a list of value
filters = {key: request.args.getlist(key) for key, value in request.args.items()}
if "limit" in filters:
result_limit = filters.pop("limit")[0]
else:
result_limit = current_app.config["SYNTHESE"]["NB_MAX_OBS_MAP"]
query = select([VSyntheseForWebApp]).order_by(VSyntheseForWebApp.date_min.desc())
synthese_query_class = SyntheseQuery(VSyntheseForWebApp, query, filters)
synthese_query_class.filter_query_all_filters(info_role)
data = DB.engine.execute(synthese_query_class.query.limit(result_limit))
# q = synthese_query.filter_query_all_filters(VSyntheseForWebApp, q, filters, info_role)
# data = q.limit(result_limit)
columns = current_app.config["SYNTHESE"]["COLUMNS_API_SYNTHESE_WEB_APP"] + MANDATORY_COLUMNS
features = []
for d in data:
feature = d.as_geofeature(fields=columns)
feature["properties"]["nom_vern_or_lb_nom"] = (
d.lb_nom if d.nom_vern is None else d.nom_vern
)
features.append(feature)
return {
"data": FeatureCollection(features),
"nb_obs_limited": len(features) == current_app.config["SYNTHESE"]["NB_MAX_OBS_MAP"],
"nb_total": len(features),
}
@routes.route("/vsynthese/<id_synthese>", methods=["GET"])
@permissions.check_cruved_scope("R", get_scope=True, module_code="SYNTHESE")
def get_one_synthese(scope, id_synthese):
"""Get one synthese record for web app with all decoded nomenclature"""
synthese = Synthese.query.join_nomenclatures().options(
joinedload("dataset").options(
selectinload("acquisition_framework").options(
joinedload("creator"),
joinedload("nomenclature_territorial_level"),
joinedload("nomenclature_financing_type"),
),
),
lazyload("areas").options(
joinedload("area_type"),
),
)
##################
fields = [
"dataset",
"dataset.acquisition_framework",
"dataset.acquisition_framework.bibliographical_references",
"dataset.acquisition_framework.cor_af_actor",
"dataset.acquisition_framework.cor_objectifs",
"dataset.acquisition_framework.cor_territories",
"dataset.acquisition_framework.cor_volets_sinp",
"dataset.acquisition_framework.creator",
"dataset.acquisition_framework.nomenclature_territorial_level",
"dataset.acquisition_framework.nomenclature_financing_type",
"dataset.cor_dataset_actor",
"dataset.cor_dataset_actor.role",
"dataset.cor_dataset_actor.organism",
"dataset.cor_territories",
"dataset.nomenclature_source_status",
"dataset.nomenclature_resource_type",
"dataset.nomenclature_dataset_objectif",
"dataset.nomenclature_data_type",
"dataset.nomenclature_data_origin",
"dataset.nomenclature_collecting_method",
"dataset.creator",
"dataset.modules",
"validations",
"validations.validation_label",
"validations.validator_role",
"cor_observers",
"cor_observers.organisme",
"source",
"habitat",
"medias",
"areas",
"areas.area_type",
]
# get reports info only if activated by admin config
alertModulesActivated = current_app.config["SYNTHESE"]["ALERT_MODULES"]
if len(alertModulesActivated) and "SYNTHESE" in alertModulesActivated:
fields.append("reports.report_type.type")
synthese = synthese.options(lazyload(Synthese.reports).joinedload(TReport.report_type))
synthese = synthese.get_or_404(id_synthese)
if not synthese.has_instance_permission(scope=scope):
raise Forbidden()
geofeature = synthese.as_geofeature(fields=Synthese.nomenclature_fields + fields)
return jsonify(geofeature)
################################
########### EXPORTS ############
################################
@routes.route("/export_taxons", methods=["POST"])
@permissions.check_cruved_scope("E", True, module_code="SYNTHESE")
def export_taxon_web(info_role):
"""Optimized route for taxon web export.
.. :quickref: Synthese;
This view is customisable by the administrator
Some columns are mandatory: cd_ref
POST parameters: Use a list of cd_ref (in POST parameters)
to filter the v_synthese_taxon_for_export_view
:query str export_format: str<'csv'>
"""
taxon_view = GenericTable(
tableName="v_synthese_taxon_for_export_view",
schemaName="gn_synthese",
engine=DB.engine,
)
columns = taxon_view.tableDef.columns
# Test de conformité de la vue v_synthese_for_export_view
try:
assert hasattr(taxon_view.tableDef.columns, "cd_ref")
except AssertionError as e:
return (
{
"msg": """
View v_synthese_taxon_for_export_view
must have a cd_ref column \n
trace: {}
""".format(
str(e)
)
},
500,
)
id_list = request.get_json()
# check R and E CRUVED to know if we filter with cruved
cruved = cruved_scope_for_user_in_module(info_role.id_role, module_code="SYNTHESE")[0]
sub_query = (
select(
[
VSyntheseForWebApp.cd_ref,
func.count(distinct(VSyntheseForWebApp.id_synthese)).label("nb_obs"),
func.min(VSyntheseForWebApp.date_min).label("date_min"),
func.max(VSyntheseForWebApp.date_max).label("date_max"),
]
)
.where(VSyntheseForWebApp.id_synthese.in_(id_list))
.group_by(VSyntheseForWebApp.cd_ref)
)
synthese_query_class = SyntheseQuery(
VSyntheseForWebApp,
sub_query,
{},
)
if cruved["R"] > cruved["E"]:
# filter on cruved
synthese_query_class.filter_query_with_cruved(info_role)
subq = synthese_query_class.query.alias("subq")
q = DB.session.query(*columns, subq.c.nb_obs, subq.c.date_min, subq.c.date_max).join(
subq, subq.c.cd_ref == columns.cd_ref
)
return to_csv_resp(
datetime.datetime.now().strftime("%Y_%m_%d_%Hh%Mm%S"),
data=serializeQuery(q.all(), q.column_descriptions),
separator=";",
columns=[db_col.key for db_col in columns] + ["nb_obs", "date_min", "date_max"],
)
@routes.route("/export_observations", methods=["POST"])
@permissions.check_cruved_scope("E", True, module_code="SYNTHESE")
def export_observations_web(info_role):
"""Optimized route for observations web export.
.. :quickref: Synthese;
This view is customisable by the administrator
Some columns are mandatory: id_synthese, geojson and geojson_local to generate the exported files
POST parameters: Use a list of id_synthese (in POST parameters) to filter the v_synthese_for_export_view
:query str export_format: str<'csv', 'geojson', 'shapefiles', 'gpkg'>
"""
params = request.args
export_format = params.get("export_format", "csv")
# Test export_format
if not export_format in current_app.config["SYNTHESE"]["EXPORT_FORMAT"]:
raise BadRequest("Unsupported format")
srid = DB.session.execute(func.Find_SRID("gn_synthese", "synthese", "the_geom_local")).scalar()
# set default to csv
export_view = GenericTableGeo(
tableName="v_synthese_for_export",
schemaName="gn_synthese",
engine=DB.engine,
geometry_field=None,
srid=srid,
)
# get list of id synthese from POST
id_list = request.get_json()
db_cols_for_shape = []
columns_to_serialize = []
# loop over synthese config to get the columns for export
for db_col in export_view.db_cols:
if db_col.key in current_app.config["SYNTHESE"]["EXPORT_COLUMNS"]:
db_cols_for_shape.append(db_col)
columns_to_serialize.append(db_col.key)
query = select([export_view.tableDef]).where(
export_view.tableDef.columns[current_app.config["SYNTHESE"]["EXPORT_ID_SYNTHESE_COL"]].in_(
id_list
)
)
synthese_query_class = SyntheseQuery(
export_view.tableDef,
query,
{},
id_synthese_column=current_app.config["SYNTHESE"]["EXPORT_ID_SYNTHESE_COL"],
id_dataset_column=current_app.config["SYNTHESE"]["EXPORT_ID_DATASET_COL"],
observers_column=current_app.config["SYNTHESE"]["EXPORT_OBSERVERS_COL"],
id_digitiser_column=current_app.config["SYNTHESE"]["EXPORT_ID_DIGITISER_COL"],
with_generic_table=True,
)
# check R and E CRUVED to know if we filter with cruved
cruved = cruved_scope_for_user_in_module(info_role.id_role, module_code="SYNTHESE")[0]
if cruved["R"] > cruved["E"]:
synthese_query_class.filter_query_with_cruved(info_role)
results = DB.session.execute(
synthese_query_class.query.limit(current_app.config["SYNTHESE"]["NB_MAX_OBS_EXPORT"])
)
file_name = datetime.datetime.now().strftime("%Y_%m_%d_%Hh%Mm%S")
file_name = filemanager.removeDisallowedFilenameChars(file_name)
if export_format == "csv":
formated_data = [export_view.as_dict(d, columns=columns_to_serialize) for d in results]
return to_csv_resp(file_name, formated_data, separator=";", columns=columns_to_serialize)
elif export_format == "geojson":
features = []
for r in results:
geometry = json.loads(
getattr(r, current_app.config["SYNTHESE"]["EXPORT_GEOJSON_4326_COL"])
)
feature = Feature(
geometry=geometry,
properties=export_view.as_dict(r, columns=columns_to_serialize),
)
features.append(feature)
results = FeatureCollection(features)
return to_json_resp(results, as_file=True, filename=file_name, indent=4)
else:
try:
dir_name, file_name = export_as_geo_file(
export_format=export_format,
export_view=export_view,
db_cols=db_cols_for_shape,
geojson_col=current_app.config["SYNTHESE"]["EXPORT_GEOJSON_LOCAL_COL"],
data=results,
file_name=file_name,
)
return send_from_directory(dir_name, file_name, as_attachment=True)
except GeonatureApiError as e:
message = str(e)
return render_template(
"error.html",
error=message,
redirect=current_app.config["URL_APPLICATION"] + "/#/synthese",
)
@routes.route("/export_metadata", methods=["GET", "POST"])
@permissions.check_cruved_scope("E", True, module_code="SYNTHESE")
def export_metadata(info_role):
"""Route to export the metadata in CSV
.. :quickref: Synthese;
The table synthese is join with gn_synthese.v_metadata_for_export
The column jdd_id is mandatory in the view gn_synthese.v_metadata_for_export
POST parameters: Use a list of id_synthese (in POST parameters) to filter the v_synthese_for_export_view
"""
if request.is_json:
filters = request.json
else:
filters = {key: request.args.getlist(key) for key, value in request.args.items()}
metadata_view = GenericTable(
tableName="v_metadata_for_export", schemaName="gn_synthese", engine=DB.engine
)
q = DB.session.query(distinct(VSyntheseForWebApp.id_dataset), metadata_view.tableDef).join(
metadata_view.tableDef,
getattr(
metadata_view.tableDef.columns,
current_app.config["SYNTHESE"]["EXPORT_METADATA_ID_DATASET_COL"],
)
== VSyntheseForWebApp.id_dataset,
)
q = select([distinct(VSyntheseForWebApp.id_dataset), metadata_view.tableDef])
synthese_query_class = SyntheseQuery(VSyntheseForWebApp, q, filters)
synthese_query_class.add_join(
metadata_view.tableDef,
getattr(
metadata_view.tableDef.columns,
current_app.config["SYNTHESE"]["EXPORT_METADATA_ID_DATASET_COL"],
),
VSyntheseForWebApp.id_dataset,
)
synthese_query_class.filter_query_all_filters(info_role)
data = DB.engine.execute(synthese_query_class.query)
return to_csv_resp(
datetime.datetime.now().strftime("%Y_%m_%d_%Hh%Mm%S"),
data=[metadata_view.as_dict(d) for d in data],
separator=";",
columns=[db_col.key for db_col in metadata_view.tableDef.columns],
)
@routes.route("/export_statuts", methods=["POST"])
@permissions.check_cruved_scope("E", True, module_code="SYNTHESE")
def export_status(info_role):
"""Route to get all the protection status of a synthese search
.. :quickref: Synthese;
Get the CRUVED from 'R' action because we don't give observations X/Y but only statuts
and to be constistant with the data displayed in the web interface
Parameters:
- HTTP-GET: the same that the /synthese endpoint (all the filter in web app)
"""
if request.is_json:
filters = request.json
else:
filters = {key: request.args.getlist(key) for key, value in request.args.items()}
# initalize the select object
q = select(
[
distinct(VSyntheseForWebApp.cd_nom),
Taxref.nom_complet,
Taxref.cd_ref,
Taxref.nom_vern,
TaxrefProtectionArticles.type_protection,
TaxrefProtectionArticles.article,
TaxrefProtectionArticles.intitule,
TaxrefProtectionArticles.arrete,
TaxrefProtectionArticles.date_arrete,
TaxrefProtectionArticles.url,
]
)
synthese_query_class = SyntheseQuery(VSyntheseForWebApp, q, filters)
# add join
synthese_query_class.add_join(Taxref, Taxref.cd_nom, VSyntheseForWebApp.cd_nom)
synthese_query_class.add_join(
TaxrefProtectionEspeces,
TaxrefProtectionEspeces.cd_nom,
VSyntheseForWebApp.cd_nom,
)
synthese_query_class.add_join(
TaxrefProtectionArticles,
TaxrefProtectionArticles.cd_protection,
TaxrefProtectionEspeces.cd_protection,
)
# filter with all get params
q = synthese_query_class.filter_query_all_filters(info_role)
data = DB.engine.execute(q)
protection_status = []
for d in data:
row = OrderedDict(
[
("nom_complet", d["nom_complet"]),
("nom_vern", d["nom_vern"]),
("cd_nom", d["cd_nom"]),
("cd_ref", d["cd_ref"]),
("type_protection", d["type_protection"]),
("article", d["article"]),
("intitule", d["intitule"]),
("arrete", d["arrete"]),
("date_arrete", d["date_arrete"]),
("url", d["url"]),
]
)
protection_status.append(row)
export_columns = [
"nom_complet",
"nom_vern",
"cd_nom",
"cd_ref",
"type_protection",
"article",
"intitule",
"arrete",
"date_arrete",
"url",
]
return to_csv_resp(
datetime.datetime.now().strftime("%Y_%m_%d_%Hh%Mm%S"),
protection_status,
separator=";",
columns=export_columns,
)
######################################
########### OTHERS ROUTES ############
######################################
@routes.route("/general_stats", methods=["GET"])
@permissions.check_cruved_scope("R", True, module_code="SYNTHESE")
@json_resp
def general_stats(info_role):
"""Return stats about synthese.
.. :quickref: Synthese;
- nb of observations
- nb of distinct species
- nb of distinct observer
- nb of datasets
"""
allowed_datasets = TDatasets.query.filter_by_readable().all()
q = select(
[
func.count(Synthese.id_synthese),
func.count(func.distinct(Synthese.cd_nom)),
func.count(func.distinct(Synthese.observers)),
]
)
synthese_query_obj = SyntheseQuery(Synthese, q, {})
synthese_query_obj.filter_query_with_cruved(info_role)
result = DB.session.execute(synthese_query_obj.query)
synthese_counts = result.fetchone()
data = {
"nb_data": synthese_counts[0],
"nb_species": synthese_counts[1],
"nb_observers": synthese_counts[2],
"nb_dataset": len(allowed_datasets),
}
return data
@routes.route("/taxons_tree", methods=["GET"])
@json_resp
def get_taxon_tree():
"""Get taxon tree.
.. :quickref: Synthese;
"""
taxon_tree_table = GenericTable(
tableName="v_tree_taxons_synthese", schemaName="gn_synthese", engine=DB.engine
)
data = DB.session.query(taxon_tree_table.tableDef).all()
return [taxon_tree_table.as_dict(d) for d in data]
@routes.route("/taxons_autocomplete", methods=["GET"])
@json_resp
def get_autocomplete_taxons_synthese():
"""Autocomplete taxon for web search (based on all taxon in Synthese).
.. :quickref: Synthese;
The request use trigram algorithm to get relevent results
:query str search_name: the search name (use sql ilike statement and puts "%" for spaces)
:query str regne: filter with kingdom
:query str group2_inpn : filter with INPN group 2
"""
search_name = request.args.get("search_name", "")
q = (
DB.session.query(
VMTaxrefListForautocomplete,
func.similarity(VMTaxrefListForautocomplete.search_name, search_name).label(
"idx_trgm"
),
)
.distinct()
.join(Synthese, Synthese.cd_nom == VMTaxrefListForautocomplete.cd_nom)
)
search_name = search_name.replace(" ", "%")
q = q.filter(VMTaxrefListForautocomplete.search_name.ilike("%" + search_name + "%"))
regne = request.args.get("regne")
if regne:
q = q.filter(VMTaxrefListForautocomplete.regne == regne)
group2_inpn = request.args.get("group2_inpn")
if group2_inpn:
q = q.filter(VMTaxrefListForautocomplete.group2_inpn == group2_inpn)
q = q.order_by(desc(VMTaxrefListForautocomplete.cd_nom == VMTaxrefListForautocomplete.cd_ref))
limit = request.args.get("limit", 20)
data = q.order_by(desc("idx_trgm")).limit(20).all()
return [d[0].as_dict() for d in data]
@routes.route("/sources", methods=["GET"])
@json_resp
def get_sources():
"""Get all sources.
.. :quickref: Synthese;
"""
q = DB.session.query(TSources)
data = q.all()
return [n.as_dict() for n in data]
@routes.route("/defaultsNomenclatures", methods=["GET"])
def getDefaultsNomenclatures():
"""Get default nomenclatures
.. :quickref: Synthese;
:query str group2_inpn:
:query str regne:
:query int organism:
"""
params = request.args
group2_inpn = "0"
regne = "0"
organism = 0
if "group2_inpn" in params:
group2_inpn = params["group2_inpn"]
if "regne" in params:
regne = params["regne"]
if "organism" in params:
organism = params["organism"]
types = request.args.getlist("mnemonique_type")
q = DB.session.query(
distinct(DefaultsNomenclaturesValue.mnemonique_type),
func.gn_synthese.get_default_nomenclature_value(
DefaultsNomenclaturesValue.mnemonique_type, organism, regne, group2_inpn
),
)
if len(types) > 0:
q = q.filter(DefaultsNomenclaturesValue.mnemonique_type.in_(tuple(types)))
data = q.all()
if not data:
raise NotFound
return jsonify(dict(data))
@routes.route("/color_taxon", methods=["GET"])
def get_color_taxon():
"""Get color of taxon in areas (vue synthese.v_color_taxon_area).
.. :quickref: Synthese;
:query str code_area_type: Type area code (ref_geo.bib_areas_types.type_code)
:query int id_area: Id of area (ref_geo.l_areas.id_area)
:query int cd_nom: taxon code (taxonomie.taxref.cd_nom)
Those three parameters can be multiples
:returns: Array<dict<VColorAreaTaxon>>
"""
params = request.args
limit = int(params.get("limit", 100))
page = params.get("page", 1, int)
if "offset" in request.args:
warn(
"offset is deprecated, please use page for pagination (start at 1)", DeprecationWarning
)
page = (int(request.args["offset"]) / limit) + 1
id_areas_type = params.getlist("code_area_type")
cd_noms = params.getlist("cd_nom")
id_areas = params.getlist("id_area")
q = DB.session.query(VColorAreaTaxon)
if len(id_areas_type) > 0:
q = q.join(LAreas, LAreas.id_area == VColorAreaTaxon.id_area).join(
BibAreasTypes, BibAreasTypes.id_type == LAreas.id_type
)
q = q.filter(BibAreasTypes.type_code.in_(tuple(id_areas_type)))
if len(id_areas) > 0:
# check if the join already done on l_areas
if not LAreas in [mapper.class_ for mapper in q._join_entities]:
q = q.join(LAreas, LAreas.id_area == VColorAreaTaxon.id_area)
q = q.filter(LAreas.id_area.in_(tuple(id_areas)))
q = q.order_by(VColorAreaTaxon.cd_nom).order_by(VColorAreaTaxon.id_area)
if len(cd_noms) > 0:
q = q.filter(VColorAreaTaxon.cd_nom.in_(tuple(cd_noms)))
results = q.paginate(page=page, per_page=limit, error_out=False)
return jsonify([d.as_dict() for d in results.items])
@routes.route("/taxa_count", methods=["GET"])
@json_resp
def get_taxa_count():
"""
Get taxa count in synthese filtering with generic parameters
.. :quickref: Synthese;
Parameters
----------
id_dataset: `int` (query parameter)
Returns
-------
count: `int`:
the number of taxon
"""
params = request.args
query = DB.session.query(func.count(distinct(Synthese.cd_nom))).select_from(Synthese)
if "id_dataset" in params:
query = query.filter(Synthese.id_dataset == params["id_dataset"])
return query.one()
@routes.route("/observation_count", methods=["GET"])
@json_resp
def get_observation_count():
"""
Get observations found in a given dataset
.. :quickref: Synthese;
Parameters
----------
id_dataset: `int` (query parameter)
Returns
-------
count: `int`:
the number of observation
"""
params = request.args
query = DB.session.query(func.count(Synthese.id_synthese)).select_from(Synthese)
if "id_dataset" in params:
query = query.filter(Synthese.id_dataset == params["id_dataset"])
return query.one()
@routes.route("/observations_bbox", methods=["GET"])
def get_bbox():
"""
Get bbbox of observations
.. :quickref: Synthese;
Parameters
-----------
id_dataset: int: (query parameter)
Returns
-------
bbox: `geojson`:
the bounding box in geojson
"""
params = request.args
query = DB.session.query(func.ST_AsGeoJSON(func.ST_Extent(Synthese.the_geom_4326)))
if "id_dataset" in params:
query = query.filter(Synthese.id_dataset == params["id_dataset"])
if "id_source" in params:
query = query.filter(Synthese.id_source == params["id_source"])
data = query.one()
if data and data[0]:
return Response(data[0], mimetype="application/json")
return "", 204
@routes.route("/observation_count_per_column/<column>", methods=["GET"])
def observation_count_per_column(column):
"""Get observations count group by a given column"""
if column not in sa.inspect(Synthese).column_attrs:
raise BadRequest(f"No column name {column} in Synthese")
synthese_column = getattr(Synthese, column)
stmt = (
DB.session.query(
func.count(Synthese.id_synthese).label("count"),
synthese_column.label(column),
)
.select_from(Synthese)
.group_by(synthese_column)
)
return jsonify(DB.session.execute(stmt).fetchall())
@routes.route("/taxa_distribution", methods=["GET"])
@json_resp
def get_taxa_distribution():
"""
Get taxa distribution for a given dataset or acquisition framework
and grouped by a certain taxa rank
"""
id_dataset = request.args.get("id_dataset")
id_af = request.args.get("id_af")
id_source = request.args.get("id_source")
rank = request.args.get("taxa_rank")
if not rank:
rank = "regne"
try:
rank = getattr(Taxref.__table__.columns, rank)
except AttributeError:
raise BadRequest("Rank does not exist")
Taxref.group2_inpn
query = (
DB.session.query(func.count(distinct(Synthese.cd_nom)), rank)
.select_from(Synthese)
.outerjoin(Taxref, Taxref.cd_nom == Synthese.cd_nom)
)
if id_dataset:
query = query.filter(Synthese.id_dataset == id_dataset)
elif id_af:
query = query.outerjoin(TDatasets, TDatasets.id_dataset == Synthese.id_dataset).filter(
TDatasets.id_acquisition_framework == id_af
)
# User can add id_source filter along with id_dataset or id_af
if id_source is not None:
query = query.filter(Synthese.id_source == id_source)
data = query.group_by(rank).all()
return [{"count": d[0], "group": d[1]} for d in data]
@routes.route("/reports", methods=["POST"])
@permissions.check_cruved_scope("R", get_scope=True, module_code="SYNTHESE")
@json_resp
def create_report(scope):
"""
Create a report (e.g report) for a given synthese id
Returns
-------
report: `json`:
Every occurrence's report
"""
session = DB.session
data = request.get_json()
if data is None:
raise BadRequest("Empty request data")
try:
type_name = data["type"]
id_synthese = data["item"]
content = data["content"]
if not id_synthese:
raise BadRequest("id_synthese is missing from the request")
if not type_name:
raise BadRequest("Report type is missing from the request")
if not content and type_name == "discussion":
raise BadRequest("Discussion content is required")
type_exists = BibReportsTypes.query.filter_by(type=type_name).first()
if not type_exists:
raise BadRequest("This report type does not exist")
synthese = Synthese.query.get_or_404(id_synthese)
if not synthese.has_instance_permission(scope):
raise Forbidden
# only allow one alert by id_synthese
if type_name in ["alert", "pin"]:
alert_exists = TReport.query.filter(
TReport.id_synthese == id_synthese,
TReport.report_type.has(BibReportsTypes.type == type_name),
).one_or_none()
if alert_exists is not None:
raise Conflict("This type already exists for this id")