-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathassets.py
More file actions
1542 lines (1435 loc) · 58.8 KB
/
assets.py
File metadata and controls
1542 lines (1435 loc) · 58.8 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
from __future__ import annotations
import json
from datetime import datetime, timedelta
from http import HTTPStatus
from humanize import naturaldelta
from flask import request, current_app
from flask_classful import FlaskView, route
from flask_login import current_user
from flask_security import auth_required
from flask_json import as_json
from flask_sqlalchemy.pagination import SelectPagination
from marshmallow import fields, ValidationError, Schema, validate
from webargs.flaskparser import use_kwargs, use_args
from sqlalchemy import select, func, or_
from flexmeasures.data.services.generic_assets import (
create_asset,
patch_asset,
delete_asset,
)
from flexmeasures.data.services.sensors import (
build_asset_jobs_data,
get_sensor_stats,
)
from flexmeasures.api.common.schemas.scheduling import (
flex_context_schema_openAPI,
storage_flex_model_schema_openAPI,
)
from flexmeasures.api.common.schemas.generic_schemas import PaginationSchema
from flexmeasures.api.common.schemas.assets import (
AssetAPIQuerySchema,
AssetPaginationSchema,
PublicAssetAPISchema,
)
from flexmeasures.data.services.job_cache import NoRedisConfigured
from flexmeasures.auth.decorators import permission_required_for_context
from flexmeasures.data import db
from flexmeasures.data.models.user import Account
from flexmeasures.data.models.audit_log import AssetAuditLog
from flexmeasures.data.models.generic_assets import GenericAsset, GenericAssetType
from flexmeasures.data.queries.generic_assets import (
filter_assets_under_root,
query_assets_by_search_terms,
)
from flexmeasures.data.schemas import AwareDateTimeField
from flexmeasures.data.schemas.generic_assets import (
GenericAssetSchema as AssetSchema,
GenericAssetIdField as AssetIdField,
GenericAssetTypeSchema as AssetTypeSchema,
SensorsToShowSchema,
)
from flexmeasures.data.schemas.scheduling import AssetTriggerSchema
from flexmeasures.data.services.scheduling import (
create_sequential_scheduling_job,
create_simultaneous_scheduling_job,
)
from flexmeasures.api.common.utils.api_utils import get_accessible_accounts
from flexmeasures.api.common.responses import (
unprocessable_entity,
request_processed,
)
from flexmeasures.api.common.schemas.users import AccountIdField
from flexmeasures.api.common.schemas.assets import default_response_fields
from flexmeasures.ui.utils.view_utils import clear_session, set_session_variables
from flexmeasures.auth.policy import check_access
from flexmeasures.data.schemas.sensors import (
SensorSchema,
)
from flexmeasures.data.models.time_series import Sensor
from flexmeasures.data.utils import get_downsample_function_and_value
asset_type_schema = AssetTypeSchema()
asset_schema = AssetSchema()
# creating this once to avoid recreating it on every request
default_list_assets_schema = AssetSchema(many=True, only=default_response_fields)
patch_asset_schema = AssetSchema(partial=True, exclude=["account_id"])
sensor_schema = SensorSchema()
sensors_schema = SensorSchema(many=True)
class AssetTriggerOpenAPISchema(AssetTriggerSchema):
def __init__(self, *args, **kwargs):
kwargs["exclude"] = ["asset"]
super().__init__(*args, **kwargs)
flex_context = fields.Nested(
flex_context_schema_openAPI,
required=True,
data_key="flex-context",
metadata=dict(
description="The flex-context is validated according to the scheduler's `FlexContextSchema`.",
),
)
flex_model = fields.Nested(
storage_flex_model_schema_openAPI(exclude=["asset"]),
required=True,
data_key="flex-model",
metadata=dict(
description="The flex-model validation is handled by the scheduler. What follows is the schema used by the `StorageScheduler`.",
),
)
class AssetChartKwargsSchema(Schema):
event_starts_after = AwareDateTimeField(format="iso", required=False)
event_ends_before = AwareDateTimeField(format="iso", required=False)
beliefs_after = AwareDateTimeField(format="iso", required=False)
beliefs_before = AwareDateTimeField(format="iso", required=False)
include_data = fields.Boolean(required=False)
combine_legend = fields.Boolean(required=False, load_default=True)
dataset_name = fields.Str(required=False)
height = fields.Str(required=False)
width = fields.Str(required=False)
chart_type = fields.Str(required=False)
class AssetChartDataKwargsSchema(Schema):
event_starts_after = AwareDateTimeField(format="iso", required=False)
event_ends_before = AwareDateTimeField(format="iso", required=False)
beliefs_after = AwareDateTimeField(format="iso", required=False)
beliefs_before = AwareDateTimeField(format="iso", required=False)
most_recent_beliefs_only = fields.Boolean(required=False)
compress_json = fields.Boolean(required=False)
class AssetAuditLogPaginationSchema(PaginationSchema):
sort_by = fields.Str(
required=False,
validate=validate.OneOf(["event_datetime"]),
)
class DefaultAssetViewJSONSchema(Schema):
default_asset_view = fields.Str(
required=True,
validate=validate.OneOf(
["Audit Log", "Context", "Graphs", "Properties", "Status"]
),
metadata={
"enum": ["Audit Log", "Context", "Graphs", "Properties", "Status"],
"description": "The default asset view to show.",
},
)
use_as_default = fields.Bool(
required=False,
load_default=True,
metadata={"description": "Whether to use this view as default."},
)
class KPIKwargsSchema(Schema):
event_starts_after = AwareDateTimeField(format="iso", required=False)
event_ends_before = AwareDateTimeField(format="iso", required=False)
class AssetTypesAPI(FlaskView):
"""
This API view exposes generic asset types.
"""
route_base = "/assets/types"
trailing_slash = False
decorators = [auth_required()]
@route("", methods=["GET"])
@as_json
def index(self):
"""
.. :quickref: Assets; Get list of available asset types
---
get:
summary: Get list of available asset types
security:
- ApiKeyAuth: []
responses:
200:
description: PROCESSED
content:
application/json:
examples:
single_asset_type:
summary: One asset type being returned in the response
value:
- id: 1
name: solar
description: solar panel(s)
tags:
- Assets
"""
response = asset_type_schema.dump(
db.session.scalars(select(GenericAssetType)).all(), many=True
)
return response, 200
class AssetAPI(FlaskView):
"""
This API view exposes generic assets.
"""
route_base = "/assets"
trailing_slash = False
decorators = [auth_required()]
@route("", methods=["GET"])
@use_kwargs(AssetAPIQuerySchema, location="query")
@as_json
def index(
self,
fields_in_response: list[str] | None,
all_accessible: bool,
include_public: bool,
account: Account | None = None,
root_asset: GenericAsset | None = None,
max_depth: int | None = None,
page: int | None = None,
per_page: int | None = None,
filter: list[str] | None = None,
sort_by: str | None = None,
sort_dir: str | None = None,
):
"""
.. :quickref: Assets; List assets accessible by the user.
---
get:
summary: List assets accessible by the user.
description: |
This endpoint returns all assets that are accessible by the user after applying optional filters.
- The `account_id` query parameter can be used to list assets from any account (if the user is allowed to read them). Per default, the user's account is used.
- Alternatively, the `all_accessible` query parameter can be used to list assets from all accounts the current_user has read-access to, plus all public assets. Defaults to `false`.
- The `include_public` query parameter can be used to include public assets in the response. Defaults to `false`.
- The `root` query parameter can be used to list only descendants of a given root asset (including the root itself).
- The `depth` query parameter can be used to search only a max number of descendant generations from the root.
The endpoint supports pagination of the asset list using the `page` and `per_page` query parameters.
- If the `page` parameter is not provided, all assets are returned, without pagination information. The result will be a list of assets.
- If a `page` parameter is provided, the response will be paginated, showing a specific number of assets per page as defined by `per_page` (default is 10).
- If a search 'filter' such as 'solar "ACME corp"' is provided, the response will filter out assets where each search term is either present in their name or account name.
The response schema for pagination is inspired by [DataTables](https://datatables.net/manual/server-side#Returned-data)
Per default, the response only includes a limited set of asset fields (id, name, account_id, generic_asset_type).
You can use the `fields` query parameter to specify a custom set of fields to include in the response.
security:
- ApiKeyAuth: []
parameters:
- in: query
schema: AssetAPIQuerySchema
responses:
200:
description: PROCESSED
content:
application/json:
examples:
single_asset:
summary: One asset being returned in the response
value:
data:
- id: 1
name: Test battery
latitude: 10
longitude: 100
account_id: 2
generic_asset_type:
id: 1
name: battery
paginated_assets:
summary: A paginated list of assets being returned in the response
value:
data:
- id: 1
name: Test battery
latitude: 10
longitude: 100
account_id: 2
generic_asset_type:
id: 1
name: battery
num-records: 1
filtered-records: 1
400:
description: INVALID_REQUEST
401:
description: UNAUTHORIZED
403:
description: INVALID_SENDER
422:
description: UNPROCESSABLE_ENTITY
tags:
- Assets
"""
# Find out which accounts are relevant
if account is not None:
check_access(account, "read")
account_ids = [account.id]
else:
use_all_accounts = all_accessible or root_asset
include_public = all_accessible or include_public or root_asset
account_ids = (
[a.id for a in get_accessible_accounts()]
if use_all_accounts
else [current_user.account.id]
)
filter_statement = GenericAsset.account_id.in_(account_ids)
if include_public:
filter_statement = filter_statement | GenericAsset.account_id.is_(None)
query = query_assets_by_search_terms(
search_terms=filter,
filter_statement=filter_statement,
sort_by=sort_by,
sort_dir=sort_dir,
)
query = filter_assets_under_root(
query=query, root_asset=root_asset, max_depth=max_depth
)
if current_app.config["FLEXMEASURES_API_SUNSET_ACTIVE"]:
# TODO: for v0.31, this is to be tested in sunset mode; in v0.32 we only do this
response_schema = default_list_assets_schema
else:
response_schema = AssetSchema(
many=True
) # in non-sunset, we default like usual, but still respect fields_in_response
if fields_in_response != default_response_fields:
response_schema = AssetSchema(many=True, only=fields_in_response)
if page is None:
response = response_schema.dump(db.session.scalars(query).all(), many=True)
else:
if per_page is None:
per_page = 10
select_pagination: SelectPagination = db.paginate(
query, per_page=per_page, page=page
)
num_records = db.session.scalar(
select(func.count(GenericAsset.id)).filter(filter_statement)
)
response = {
"data": response_schema.dump(select_pagination.items, many=True),
"num-records": num_records,
"filtered-records": select_pagination.total,
}
return response, 200
@route(
"/<id>/sensors",
methods=["GET"],
)
@use_kwargs(
{
"asset": AssetIdField(data_key="id"),
},
location="path",
)
@use_kwargs(AssetPaginationSchema, location="query")
@as_json
def asset_sensors(
self,
id: int,
asset: GenericAsset | None,
page: int | None = None,
per_page: int | None = None,
filter: list[str] | None = None,
sort_by: str | None = None,
sort_dir: str | None = None,
):
"""
.. :quickref: Assets; Return all sensors under an asset.
---
get:
summary: Return all sensors under an asset.
description: |
This endpoint returns all sensors under an asset.
The endpoint supports pagination of the asset list using the `page` and `per_page` query parameters.
- If the `page` parameter is not provided, all sensors are returned, without pagination information. The result will be a list of sensors.
- If a `page` parameter is provided, the response will be paginated, showing a specific number of assets per page as defined by `per_page` (default is 10).
The response schema for pagination is inspired by https://datatables.net/manual/server-side#Returned-data
security:
- ApiKeyAuth: []
parameters:
- in: path
name: id
description: ID of the asset to fetch sensors for
schema:
type: integer
- in: query
schema: AssetPaginationSchema
responses:
200:
description: PROCESSED
content:
application/json:
examples:
single_asset:
summary: One asset being returned in the response
value:
data:
- id: 1
name: Test battery
latitude: 10
longitude: 100
account_id: 2
generic_asset_type:
id: 1
name: battery
paginated_assets:
summary: A paginated list of assets being returned in the response
value:
data:
- id: 1
name: Test battery
latitude: 10
longitude: 100
account_id: 2
generic_asset_type:
id: 1
name: battery
num-records: 1
filtered-records: 1
400:
description: INVALID_REQUEST
401:
description: UNAUTHORIZED
403:
description: INVALID_SENDER
422:
description: UNPROCESSABLE_ENTITY
tags:
- Assets
"""
query_statement = Sensor.generic_asset_id == asset.id
query = select(Sensor).filter(query_statement)
if filter:
search_terms = filter[0].split(" ")
query = query.filter(
or_(*[Sensor.name.ilike(f"%{term}%") for term in search_terms])
)
if sort_by is not None and sort_dir is not None:
valid_sort_columns = {
"id": Sensor.id,
"name": Sensor.name,
"resolution": Sensor.event_resolution,
}
query = query.order_by(
valid_sort_columns[sort_by].asc()
if sort_dir == "asc"
else valid_sort_columns[sort_by].desc()
)
select_pagination: SelectPagination = db.paginate(
query, per_page=per_page, page=page
)
num_records = db.session.scalar(
select(func.count(Sensor.id)).where(query_statement)
)
sensors_response: list = [
{
**sensor_schema.dump(sensor),
"event_resolution": naturaldelta(sensor.event_resolution),
}
for sensor in select_pagination.items
]
response = {
"data": sensors_response,
"num-records": num_records,
"filtered-records": select_pagination.total,
}
return response, 200
@route("/public", methods=["GET"])
@use_kwargs(PublicAssetAPISchema, location="query")
@as_json
def public(self, fields_in_response: list[str] | None):
"""
.. :quickref: Assets; Return all public assets.
---
get:
summary: Return all public assets.
description: This endpoint returns all public assets.
security:
- ApiKeyAuth: []
parameters:
- in: query
schema: PublicAssetAPISchema
responses:
200:
description: PROCESSED
400:
description: INVALID_REQUEST
401:
description: UNAUTHORIZED
422:
description: UNPROCESSABLE_ENTITY
tags:
- Assets
"""
assets = db.session.scalars(
select(GenericAsset).filter(GenericAsset.account_id.is_(None))
).all()
if current_app.config["FLEXMEASURES_API_SUNSET_ACTIVE"]:
# TODO: for v0.31, this is to be tested in sunset mode; in v0.32 we only do this
response_schema = default_list_assets_schema
else:
response_schema = AssetSchema(
many=True
) # in non-sunset, we default like usual, but still respect fields_in_response
if fields_in_response != default_response_fields:
response_schema = AssetSchema(many=True, only=fields_in_response)
return response_schema.dump(assets), 200
@route("", methods=["POST"])
@permission_required_for_context(
"create-children", ctx_loader=AccountIdField.load_current
)
@use_args(asset_schema)
def post(self, asset_data: dict):
"""
.. :quickref: Assets; Creates a new asset.
---
post:
summary: Creates a new asset.
description: |
This endpoint creates a new asset.
To establish a hierarchical relationship, you can optionally include the **parent_asset_id** in the request body to make the new asset a child of an existing asset.
security:
- ApiKeyAuth: []
requestBody:
content:
application/json:
schema: AssetSchema
examples:
single_asset:
summary: Request to create a standalone asset
value:
name: Test battery
generic_asset_type_id: 2
account_id: 2
latitude: 40
longitude: 170.3
child_asset:
summary: Request to create an asset with a parent
value:
name: Test battery
generic_asset_type_id: 2
account_id: 2
parent_asset_id: 10
latitude: 40
longitude: 170.3
responses:
201:
description: PROCESSED
content:
application/json:
examples:
single_asset:
summary: One asset being returned in the response
value:
generic_asset_type_id: 2
name: Test battery
id: 1
latitude: 10
longitude: 100
account_id: 1
child_asset:
summary: A child asset being returned in the response
value:
generic_asset_type_id: 2
name: Test battery
id: 1
latitude: 10
longitude: 100
account_id: 1
400:
description: INVALID_REQUEST
401:
description: UNAUTHORIZED
403:
description: INVALID_SENDER
422:
description: UNPROCESSABLE_ENTITY
tags:
- Assets
"""
asset = create_asset(asset_data)
db.session.commit()
return asset_schema.dump(asset), 201
@route("/<id>", methods=["GET"])
@use_kwargs(
{
"asset": AssetIdField(
data_key="id", status_if_not_found=HTTPStatus.NOT_FOUND
)
},
location="path",
)
@permission_required_for_context("read", ctx_arg_name="asset")
@as_json
def fetch_one(self, id, asset):
"""
.. :quickref: Assets; Fetch a given asset.
---
get:
summary: Fetch a given asset.
description: This endpoint gets an asset.
security:
- ApiKeyAuth: []
parameters:
- in: path
name: id
description: ID of the asset to fetch.
schema:
type: integer
responses:
200:
description: PROCESSED
content:
application/json:
examples:
single_asset:
summary: One asset being returned in the response
value:
generic_asset_type_id: 2
name: Test battery
id: 1
latitude: 10
longitude: 100
account_id: 1
400:
description: INVALID_REQUEST, REQUIRED_INFO_MISSING, UNEXPECTED_PARAMS
401:
description: UNAUTHORIZED
403:
description: INVALID_SENDER
422:
description: UNPROCESSABLE_ENTITY
tags:
- Assets
"""
return asset_schema.dump(asset), 200
@route("/<id>", methods=["PATCH"])
@use_kwargs(
{
"db_asset": AssetIdField(
data_key="id", status_if_not_found=HTTPStatus.NOT_FOUND
)
},
location="path",
)
@permission_required_for_context("update", ctx_arg_name="db_asset")
@as_json
def patch(self, id: int, db_asset: GenericAsset):
"""
.. :quickref: Assets; Update an asset given its identifier.
---
patch:
summary: Update an asset given its identifier.
description: |
This endpoint sets data for an existing asset.
Any subset of asset fields can be sent.
The following fields are not allowed to be updated:
- id
- account_id
security:
- ApiKeyAuth: []
parameters:
- in: path
name: id
description: ID of the asset to update.
schema:
type: integer
requestBody:
content:
application/json:
schema: AssetSchema
examples:
single_asset:
summary: One asset being updated
value:
latitude: 11.1
longitude: 99.9
responses:
200:
description: PROCESSED
content:
application/json:
examples:
single_asset:
summary: the whole asset is returned in the response
value:
generic_asset_type_id: 2
name: Test battery
id: 1
latitude: 11.1
longitude: 99.9
account_id: 1
external_id: ""
400:
description: INVALID_REQUEST, REQUIRED_INFO_MISSING, UNEXPECTED_PARAMS
401:
description: UNAUTHORIZED
403:
description: INVALID_SENDER
422:
description: UNPROCESSABLE_ENTITY
tags:
- Assets
"""
# For us to be able to add our own context, we need to validate the data ourselves
asset_data = request.get_json()
if not asset_data:
return unprocessable_entity("No JSON data provided.")
asset_schema = AssetSchema(partial=True)
asset_schema.context = {
"asset": db_asset
} # context for validating fields like parent_asset_id
try:
validated_data = asset_schema.load(asset_data)
except ValidationError as e:
return unprocessable_entity(e.messages)
try:
db_asset = patch_asset(db_asset, validated_data)
except ValidationError as e:
return unprocessable_entity(e.messages)
db.session.add(db_asset)
db.session.commit()
return asset_schema.dump(db_asset), 200
@route("/<id>", methods=["DELETE"])
@use_kwargs(
{
"asset": AssetIdField(
data_key="id", status_if_not_found=HTTPStatus.NOT_FOUND
)
},
location="path",
)
@permission_required_for_context("delete", ctx_arg_name="asset")
@as_json
def delete(self, id: int, asset: GenericAsset):
"""
.. :quickref: Assets; Delete an asset.
---
delete:
summary: Delete an asset.
description: This endpoint deletes an existing asset, as well as all sensors and measurements recorded for it.
security:
- ApiKeyAuth: []
parameters:
- in: path
name: id
description: ID of the asset to delete.
schema:
type: integer
responses:
204:
description: DELETED
400:
description: INVALID_REQUEST, REQUIRED_INFO_MISSING, UNEXPECTED_PARAMS
401:
description: UNAUTHORIZED
403:
description: INVALID_SENDER
422:
description: UNPROCESSABLE_ENTITY
tags:
- Assets
"""
delete_asset(asset)
db.session.commit()
return {}, 204
@route("/<id>/chart", strict_slashes=False) # strict on next version? see #1014
@use_kwargs(
{
"asset": AssetIdField(
data_key="id", status_if_not_found=HTTPStatus.NOT_FOUND
)
},
location="path",
)
@use_kwargs(AssetChartKwargsSchema, location="query")
@permission_required_for_context("read", ctx_arg_name="asset")
def get_chart(self, id: int, asset: GenericAsset, **kwargs):
"""
.. :quickref: Charts; Download an embeddable chart with time series data
---
get:
summary: Download an embeddable chart with time series data
description: |
This endpoint returns a chart with time series for an asset.
The response contains the HTML and JavaScript needed to embedded and render the chart in an HTML page.
This is used by the FlexMeasures UI.
To learn how to embed the response in your web page, see [this section](https://flexmeasures.readthedocs.io/latest/tut/building_uis.html#embedding-charts) in the developer documentation.
security:
- ApiKeyAuth: []
parameters:
- in: path
name: id
description: ID of the asset to download a chart for.
schema:
type: integer
- in: query
schema: AssetChartKwargsSchema
responses:
200:
description: PROCESSED
400:
description: INVALID_REQUEST, REQUIRED_INFO_MISSING, UNEXPECTED_PARAMS
401:
description: UNAUTHORIZED
403:
description: INVALID_SENDER
422:
description: UNPROCESSABLE_ENTITY
tags:
- Assets
"""
# Store selected time range as session variables, for a consistent UX across UI page loads
set_session_variables("event_starts_after", "event_ends_before")
return json.dumps(asset.chart(**kwargs))
@route(
"/<id>/chart_data", strict_slashes=False
) # strict on next version? see #1014
@use_kwargs(
{
"asset": AssetIdField(
data_key="id", status_if_not_found=HTTPStatus.NOT_FOUND
)
},
location="path",
)
@use_kwargs(
{
"event_starts_after": AwareDateTimeField(format="iso", required=False),
"event_ends_before": AwareDateTimeField(format="iso", required=False),
"beliefs_after": AwareDateTimeField(format="iso", required=False),
"beliefs_before": AwareDateTimeField(format="iso", required=False),
"use_latest_version_per_event": fields.Boolean(
required=False, load_default=False
),
"most_recent_beliefs_only": fields.Boolean(required=False),
"compress_json": fields.Boolean(required=False),
},
location="query",
)
@permission_required_for_context("read", ctx_arg_name="asset")
def get_chart_data(self, id: int, asset: GenericAsset, **kwargs):
"""
.. :quickref: Charts; Download time series for use in charts
---
get:
summary: Download time series for use in charts
description: Data for use in charts (in case you have the chart specs already).
security:
- ApiKeyAuth: []
parameters:
- in: path
name: id
description: ID of the asset to download data for.
schema:
type: integer
- in: query
schema: AssetChartDataKwargsSchema
responses:
200:
description: PROCESSED
content:
application/json:
schema:
type: object
400:
description: INVALID_REQUEST, REQUIRED_INFO_MISSING, UNEXPECTED_PARAMS
401:
description: UNAUTHORIZED
403:
description: INVALID_SENDER
422:
description: UNPROCESSABLE_ENTITY
tags:
- Assets
"""
sensors = SensorsToShowSchema.flatten(asset.validate_sensors_to_show())
return asset.search_beliefs(sensors=sensors, as_json=True, **kwargs)
@route("/<id>/auditlog")
@use_kwargs(
{"asset": AssetIdField(data_key="id")},
location="path",
)
@permission_required_for_context("read", ctx_arg_name="asset")
@use_kwargs(AssetAuditLogPaginationSchema, location="query")
@as_json
def auditlog(
self,
id: int,
asset: GenericAsset,
page: int | None = None,
per_page: int | None = None,
filter: list[str] | None = None,
sort_by: str | None = None,
sort_dir: str | None = None,
):
"""
.. :quickref: Assets; Get history of asset related actions.
---
get:
summary: Get history of asset related actions.
description: |
The endpoint is paginated and supports search filters.
- If the `page` parameter is not provided, all audit logs are returned paginated by `per_page` (default is 10).
- If a `page` parameter is provided, the response will be paginated, showing a specific number of assets per page as defined by `per_page` (default is 10).
- If `sort_by` (field name) and `sort_dir` ("asc" or "desc") are provided, the list will be sorted.
- If a search 'filter' is provided, the response will filter out audit logs where each search term is either present in the event or active user name.
The response schema for pagination is inspired by [DataTables](https://datatables.net/manual/server-side)
security:
- ApiKeyAuth: []
parameters:
- in: path
name: id
required: true
description: ID of the asset to get the history for.
schema:
type: integer
- in: query
schema: AssetAuditLogPaginationSchema
responses:
200:
description: PROCESSED
content:
application/json:
schema:
type: object
examples:
pagination:
summary: Pagination response
value:
data:
- event: Asset test asset deleted
event_datetime: "2021-01-01T00:00:00"
active_user_name: 'Test user'
num_records: 1,
filtered_records: 1
400:
description: INVALID_REQUEST, REQUIRED_INFO_MISSING, UNEXPECTED_PARAMS
401:
description: UNAUTHORIZED
403:
description: INVALID_SENDER
422:
description: UNPROCESSABLE_ENTITY
tags:
- Assets
"""
query_statement = AssetAuditLog.affected_asset_id == asset.id
query = select(AssetAuditLog).filter(query_statement)
if filter:
search_terms = filter[0].split(" ")
query = query.filter(
or_(
*[AssetAuditLog.event.ilike(f"%{term}%") for term in search_terms],
*[
AssetAuditLog.active_user_name.ilike(f"%{term}%")
for term in search_terms
],
)
)