-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcb.py
1935 lines (1763 loc) · 78.9 KB
/
cb.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
"""
Context Broker Module for API Client
"""
from __future__ import annotations
from copy import deepcopy
from math import inf
from pkg_resources import parse_version
from pydantic import \
parse_obj_as, \
PositiveInt, \
PositiveFloat, \
AnyHttpUrl
from typing import Any, Dict, List , Optional, TYPE_CHECKING, Union
from packaging import version
import re
import requests
from urllib.parse import urljoin
import warnings
from filip.clients.base_http_client import BaseHttpClient
from filip.config import settings
from filip.models.base import FiwareHeader, PaginationMethod
from filip.utils.simple_ql import QueryString
from filip.models.ngsi_v2.context import \
ActionType, \
Command, \
ContextEntity, \
ContextEntityKeyValues, \
ContextAttribute, \
NamedCommand, \
NamedContextAttribute, \
Query, \
Update, \
PropertyFormat
from filip.models.ngsi_v2.base import AttrsFormat
from filip.models.ngsi_v2.subscriptions import Subscription, Message
from filip.models.ngsi_v2.registrations import Registration
if TYPE_CHECKING:
from filip.clients.ngsi_v2.iota import IoTAClient
class ContextBrokerClient(BaseHttpClient):
"""
Implementation of NGSI Context Broker functionalities, such as creating
entities and subscriptions; retrieving, updating and deleting data.
Further documentation:
https://fiware-orion.readthedocs.io/en/master/
Api specifications for v2 are located here:
https://telefonicaid.github.io/fiware-orion/api/v2/stable/
Note:
We use the reference implementation for development. Therefore, some
other brokers may show slightly different behavior!
"""
def __init__(self,
url: str = None,
*,
session: requests.Session = None,
fiware_header: FiwareHeader = None,
**kwargs):
"""
Args:
url: Url of context broker server
session (requests.Session):
fiware_header (FiwareHeader): fiware service and fiware service path
**kwargs (Optional): Optional arguments that ``request`` takes.
"""
# set service url
url = url or settings.CB_URL
super().__init__(url=url,
session=session,
fiware_header=fiware_header,
**kwargs)
self._check_correct_cb_version()
def __pagination(self,
*,
method: PaginationMethod = PaginationMethod.GET,
url: str,
headers: Dict,
limit: Union[PositiveInt, PositiveFloat] = None,
params: Dict = None,
data: str = None) -> List[Dict]:
"""
NGSIv2 implements a pagination mechanism in order to help clients to
retrieve large sets of resources. This mechanism works for all listing
operations in the API (e.g. GET /v2/entities, GET /v2/subscriptions,
POST /v2/op/query, etc.). This function helps getting datasets that are
larger than the limit for the different GET operations.
https://fiware-orion.readthedocs.io/en/master/user/pagination/index.html
Args:
url: Information about the url, obtained from the original function
headers: The headers from the original function
params:
limit:
Returns:
object:
"""
if limit is None:
limit = inf
if limit > 1000:
params['limit'] = 1000 # maximum items per request
else:
params['limit'] = limit
if self.session:
session = self.session
else:
session = requests.Session()
with session:
res = session.request(method=method,
url=url,
params=params,
headers=headers,
data=data)
if res.ok:
items = res.json()
# do pagination
count = int(res.headers['Fiware-Total-Count'])
while len(items) < limit and len(items) < count:
# Establishing the offset from where entities are retrieved
params['offset'] = len(items)
params['limit'] = min(1000, (limit - len(items)))
res = session.request(method=method,
url=url,
params=params,
headers=headers,
data=data)
if res.ok:
items.extend(res.json())
else:
res.raise_for_status()
self.logger.debug('Received: %s', items)
return items
res.raise_for_status()
# MANAGEMENT API
def get_version(self) -> Dict:
"""
Gets version of IoT Agent
Returns:
Dictionary with response
"""
url = urljoin(self.base_url, '/version')
try:
res = self.get(url=url, headers=self.headers)
if res.ok:
return res.json()
res.raise_for_status()
except requests.RequestException as err:
self.logger.error(err)
raise
def _check_correct_cb_version(self) -> None:
"""
Checks whether the used Orion version is greater or equal than the minimum required orion version of
the current filip version
"""
orion_version = self.get_version()['orion']['version']
if version.parse(orion_version) < version.parse(settings.minimum_orion_version):
warnings.warn(
f"You are using orion version {orion_version}. There was a breaking change in Orion Version "
f"{settings.minimum_orion_version}, therefore functionality is not assured when using "
f"version {orion_version}."
)
def get_resources(self) -> Dict:
"""
Gets reo
Returns:
Dict
"""
url = urljoin(self.base_url, '/v2')
try:
res = self.get(url=url, headers=self.headers)
if res.ok:
return res.json()
res.raise_for_status()
except requests.RequestException as err:
self.logger.error(err)
raise
# STATISTICS API
def get_statistics(self) -> Dict:
"""
Gets statistics of context broker
Returns:
Dictionary with response
"""
url = urljoin(self.base_url, 'statistics')
try:
res = self.get(url=url, headers=self.headers)
if res.ok:
return res.json()
res.raise_for_status()
except requests.RequestException as err:
self.logger.error(err)
raise
# CONTEXT MANAGEMENT API ENDPOINTS
# Entity Operations
def post_entity(self,
entity: ContextEntity,
update: bool = False,
patch: bool = False,
override_attr_metadata: bool = True
):
"""
Function registers an Object with the NGSI Context Broker,
if it already exists it can be automatically updated (overwritten)
if the update bool is True.
First a post request with the entity is tried, if the response code
is 422 the entity is uncrossable, as it already exists there are two
options, either overwrite it, if the attribute have changed
(e.g. at least one new/new values) (update = True) or leave
it the way it is (update=False)
If you only want to manipulate the entities values, you need to set
patch argument.
Args:
entity (ContextEntity):
Context Entity Object
update (bool):
If the response.status_code is 422, whether the override and
existing entity
patch (bool):
If the response.status_code is 422, whether the manipulate the
existing entity. Omitted if update `True`.
override_attr_metadata:
Only applies for patch equal to `True`.
Whether to override or append the attributes metadata.
`True` for overwrite or `False` for update/append
"""
url = urljoin(self.base_url, 'v2/entities')
headers = self.headers.copy()
try:
res = self.post(
url=url,
headers=headers,
json=entity.dict(exclude_unset=True,
exclude_defaults=True,
exclude_none=True))
if res.ok:
self.logger.info("Entity successfully posted!")
return res.headers.get('Location')
res.raise_for_status()
except requests.RequestException as err:
if update and err.response.status_code == 422:
return self.update_entity(
entity=entity)
if patch and err.response.status_code == 422:
return self.patch_entity(
entity=entity,
override_attr_metadata=override_attr_metadata)
msg = f"Could not post entity {entity.id}"
self.log_error(err=err, msg=msg)
raise
def get_entity_list(self,
*,
entity_ids: List[str] = None,
entity_types: List[str] = None,
id_pattern: str = None,
type_pattern: str = None,
q: Union[str, QueryString] = None,
mq: Union[str, QueryString] = None,
georel: str = None,
geometry: str = None,
coords: str = None,
limit: PositiveInt = inf,
attrs: List[str] = None,
metadata: str = None,
order_by: str = None,
response_format: Union[AttrsFormat, str] =
AttrsFormat.NORMALIZED
) -> List[Union[ContextEntity,
ContextEntityKeyValues,
Dict[str, Any]]]:
r"""
Retrieves a list of context entities that match different criteria by
id, type, pattern matching (either id or type) and/or those which
match a query or geographical query (see Simple Query Language and
Geographical Queries). A given entity has to match all the criteria
to be retrieved (i.e., the criteria is combined in a logical AND
way). Note that pattern matching query parameters are incompatible
(i.e. mutually exclusive) with their corresponding exact matching
parameters, i.e. idPattern with id and typePattern with type.
Args:
entity_ids: A comma-separated list of elements. Retrieve entities
whose ID matches one of the elements in the list.
Incompatible with idPattern,e.g. Boe_Idarium
entity_types: comma-separated list of elements. Retrieve entities
whose type matches one of the elements in the list.
Incompatible with typePattern. Example: Room.
id_pattern: A correctly formatted regular expression. Retrieve
entities whose ID matches the regular expression. Incompatible
with id, e.g. ngsi-ld.* or sensor.*
type_pattern: A correctly formatted regular expression. Retrieve
entities whose type matches the regular expression.
Incompatible with type, e.g. room.*
q (SimpleQuery): A query expression, composed of a list of
statements separated by ;, i.e.,
q=statement1;statement2;statement3. See Simple Query
Language specification. Example: temperature>40.
mq (SimpleQuery): A query expression for attribute metadata,
composed of a list of statements separated by ;, i.e.,
mq=statement1;statement2;statement3. See Simple Query
Language specification. Example: temperature.accuracy<0.9.
georel: Spatial relationship between matching entities and a
reference shape. See Geographical Queries. Example: 'near'.
geometry: Geographical area to which the query is restricted.
See Geographical Queries. Example: point.
coords: List of latitude-longitude pairs of coordinates separated
by ';'. See Geographical Queries. Example: 41.390205,
2.154007;48.8566,2.3522.
limit: Limits the number of entities to be retrieved Example: 20
attrs: Comma-separated list of attribute names whose data are to
be included in the response. The attributes are retrieved in
the order specified by this parameter. If this parameter is
not included, the attributes are retrieved in arbitrary
order. See "Filtering out attributes and metadata" section
for more detail. Example: seatNumber.
metadata: A list of metadata names to include in the response.
See "Filtering out attributes and metadata" section for more
detail. Example: accuracy.
order_by: Criteria for ordering results. See "Ordering Results"
section for details. Example: temperature,!speed.
response_format (AttrsFormat, str): Response Format. Note: That if
'keyValues' or 'values' are used the response model will
change to List[ContextEntityKeyValues] and to List[Dict[str,
Any]], respectively.
Returns:
"""
url = urljoin(self.base_url, 'v2/entities/')
headers = self.headers.copy()
params = {}
if entity_ids and id_pattern:
raise ValueError
if entity_types and type_pattern:
raise ValueError
if entity_ids:
if not isinstance(entity_ids, list):
entity_ids = [entity_ids]
params.update({'id': ','.join(entity_ids)})
if id_pattern:
try:
re.compile(id_pattern)
except re.error as err:
raise ValueError(f'Invalid Pattern: {err}') from err
params.update({'idPattern': id_pattern})
if entity_types:
if not isinstance(entity_types, list):
entity_types = [entity_types]
params.update({'type': ','.join(entity_types)})
if type_pattern:
try:
re.compile(type_pattern)
except re.error as err:
raise ValueError(f'Invalid Pattern: {err.msg}') from err
params.update({'typePattern': type_pattern})
if attrs:
params.update({'attrs': ','.join(attrs)})
if metadata:
params.update({'metadata': ','.join(metadata)})
if q:
if isinstance(q, str):
q = QueryString.parse_str(q)
params.update({'q': str(q)})
if mq:
params.update({'mq': str(mq)})
if geometry:
params.update({'geometry': geometry})
if georel:
params.update({'georel': georel})
if coords:
params.update({'coords': coords})
if order_by:
params.update({'orderBy': order_by})
if response_format not in list(AttrsFormat):
raise ValueError(f'Value must be in {list(AttrsFormat)}')
response_format = ','.join(['count', response_format])
params.update({'options': response_format})
try:
items = self.__pagination(method=PaginationMethod.GET,
limit=limit,
url=url,
params=params,
headers=headers)
if AttrsFormat.NORMALIZED in response_format:
return parse_obj_as(List[ContextEntity], items)
if AttrsFormat.KEY_VALUES in response_format:
return parse_obj_as(List[ContextEntityKeyValues], items)
return items
except requests.RequestException as err:
msg = "Could not load entities"
self.log_error(err=err, msg=msg)
raise
def get_entity(self,
entity_id: str,
entity_type: str = None,
attrs: List[str] = None,
metadata: List[str] = None,
response_format: Union[AttrsFormat, str] =
AttrsFormat.NORMALIZED) \
-> Union[ContextEntity, ContextEntityKeyValues, Dict[str, Any]]:
"""
This operation must return one entity element only, but there may be
more than one entity with the same ID (e.g. entities with same ID but
different types). In such case, an error message is returned, with
the HTTP status code set to 409 Conflict.
Args:
entity_id (String): Id of the entity to be retrieved
entity_type (String): Entity type, to avoid ambiguity in case
there are several entities with the same entity id.
attrs (List of Strings): List of attribute names whose data must be
included in the response. The attributes are retrieved in the
order specified by this parameter.
See "Filtering out attributes and metadata" section for more
detail. If this parameter is not included, the attributes are
retrieved in arbitrary order, and all the attributes of the
entity are included in the response.
Example: temperature, humidity.
metadata (List of Strings): A list of metadata names to include in
the response. See "Filtering out attributes and metadata"
section for more detail. Example: accuracy.
response_format (AttrsFormat, str): Representation format of
response
Returns:
ContextEntity
"""
url = urljoin(self.base_url, f'v2/entities/{entity_id}')
headers = self.headers.copy()
params = {}
if entity_type:
params.update({'type': entity_type})
if attrs:
params.update({'attrs': ','.join(attrs)})
if metadata:
params.update({'metadata': ','.join(metadata)})
if response_format not in list(AttrsFormat):
raise ValueError(f'Value must be in {list(AttrsFormat)}')
params.update({'options': response_format})
try:
res = self.get(url=url, params=params, headers=headers)
if res.ok:
self.logger.info("Entity successfully retrieved!")
self.logger.debug("Received: %s", res.json())
if response_format == AttrsFormat.NORMALIZED:
return ContextEntity(**res.json())
if response_format == AttrsFormat.KEY_VALUES:
return ContextEntityKeyValues(**res.json())
return res.json()
res.raise_for_status()
except requests.RequestException as err:
msg = f"Could not load entity {entity_id}"
self.log_error(err=err, msg=msg)
raise
def get_entity_attributes(self,
entity_id: str,
entity_type: str = None,
attrs: List[str] = None,
metadata: List[str] = None,
response_format: Union[AttrsFormat, str] =
AttrsFormat.NORMALIZED) -> \
Dict[str, ContextAttribute]:
"""
This request is similar to retrieving the whole entity, however this
one omits the id and type fields. Just like the general request of
getting an entire entity, this operation must return only one entity
element. If more than one entity with the same ID is found (e.g.
entities with same ID but different type), an error message is
returned, with the HTTP status code set to 409 Conflict.
Args:
entity_id (String): Id of the entity to be retrieved
entity_type (String): Entity type, to avoid ambiguity in case
there are several entities with the same entity id.
attrs (List of Strings): List of attribute names whose data must be
included in the response. The attributes are retrieved in the
order specified by this parameter.
See "Filtering out attributes and metadata" section for more
detail. If this parameter is not included, the attributes are
retrieved in arbitrary order, and all the attributes of the
entity are included in the response. Example: temperature,
humidity.
metadata (List of Strings): A list of metadata names to include in
the response. See "Filtering out attributes and metadata"
section for more detail. Example: accuracy.
response_format (AttrsFormat, str): Representation format of
response
Returns:
Dict
"""
url = urljoin(self.base_url, f'v2/entities/{entity_id}/attrs')
headers = self.headers.copy()
params = {}
if entity_type:
params.update({'type': entity_type})
if attrs:
params.update({'attrs': ','.join(attrs)})
if metadata:
params.update({'metadata': ','.join(metadata)})
if response_format not in list(AttrsFormat):
raise ValueError(f'Value must be in {list(AttrsFormat)}')
params.update({'options': response_format})
try:
res = self.get(url=url, params=params, headers=headers)
if res.ok:
if response_format == AttrsFormat.NORMALIZED:
return {key: ContextAttribute(**values)
for key, values in res.json().items()}
return res.json()
res.raise_for_status()
except requests.RequestException as err:
msg = f"Could not load attributes from entity {entity_id} !"
self.log_error(err=err, msg=msg)
raise
def update_entity(self,
entity: ContextEntity,
append_strict: bool = False
):
"""
The request payload is an object representing the attributes to
append or update.
Note:
Update means overwriting the existing entity. If you want to
manipulate you should rather use patch_entity.
Args:
entity (ContextEntity):
append_strict: If `False` the entity attributes are updated (if they
previously exist) or appended (if they don't previously exist)
with the ones in the payload.
If `True` all the attributes in the payload not
previously existing in the entity are appended. In addition
to that, in case some of the attributes in the payload
already exist in the entity, an error is returned.
More precisely this means a strict append procedure.
Returns:
None
"""
self.update_or_append_entity_attributes(entity_id=entity.id,
entity_type=entity.type,
attrs=entity.get_properties(),
append_strict=append_strict)
def delete_entity(self,
entity_id: str,
entity_type: str,
delete_devices: bool = False,
iota_client: IoTAClient = None,
iota_url: AnyHttpUrl = settings.IOTA_URL) -> None:
"""
Remove a entity from the context broker. No payload is required
or received.
Args:
entity_id:
Id of the entity to be deleted
entity_type:
several entities with the same entity id.
delete_devices:
If True, also delete all devices that reference this
entity (entity_id as entity_name)
iota_client:
Corresponding IoTA-Client used to access IoTA-Agent
iota_url:
URL of the corresponding IoT-Agent. This will autogenerate
an IoTA-Client, mirroring the information of the
ContextBrokerClient, e.g. FiwareHeader, and other headers
Returns:
None
"""
url = urljoin(self.base_url, f'v2/entities/{entity_id}')
headers = self.headers.copy()
params = {'type': entity_type}
try:
res = self.delete(url=url, params=params, headers=headers)
if res.ok:
self.logger.info("Entity '%s' successfully deleted!", entity_id)
else:
res.raise_for_status()
except requests.RequestException as err:
msg = f"Could not delete entity {entity_id} !"
self.log_error(err=err, msg=msg)
raise
if delete_devices:
from filip.clients.ngsi_v2 import IoTAClient
if iota_client:
iota_client_local = deepcopy(iota_client)
else:
warnings.warn("No IoTA-Client object provided! "
"Will try to generate one. "
"This usage is not recommended.")
iota_client_local = IoTAClient(
url=iota_url,
fiware_header=self.fiware_headers,
headers=self.headers)
for device in iota_client_local.get_device_list(
entity_names=[entity_id]):
if device.entity_type == entity_type:
iota_client_local.delete_device(device_id=device.device_id)
iota_client_local.close()
def delete_entities(self, entities: List[ContextEntity]) -> None:
"""
Remove a list of entities from the context broker. This methode is
more efficient than to call delete_entity() for each entity
Args:
entities: List[ContextEntity]: List of entities to be deleted
Raises:
Exception, if one of the entities is not in the ContextBroker
Returns:
None
"""
# update() delete, deletes all entities without attributes completely,
# and removes the attributes for the other
# The entities are sorted based on the fact if they have
# attributes.
entities_with_attributes: List[ContextEntity] = []
for entity in entities:
attribute_names = [key for key in entity.dict() if key not in
ContextEntity.__fields__]
if len(attribute_names) > 0:
entities_with_attributes.append(
ContextEntity(id=entity.id, type=entity.type))
# Post update_delete for those without attribute only once,
# for the other post update_delete again but for the changed entity
# in the ContextBroker (only id and type left)
if len(entities) > 0:
self.update(entities=entities, action_type="delete")
if len(entities_with_attributes) > 0:
self.update(entities=entities_with_attributes, action_type="delete")
def update_or_append_entity_attributes(
self,
entity_id: str,
entity_type: str,
attrs: List[Union[NamedContextAttribute,
Dict[str, ContextAttribute]]],
append_strict: bool = False):
"""
The request payload is an object representing the attributes to
append or update. This corresponds to a 'POST' request if append is
set to 'False'
Note:
Be careful not to update attributes that are
provided via context registration, e.g. commands. Commands are
removed before sending the request. To avoid breaking things.
Args:
entity_id: Entity id to be updated
entity_type: Entity type, to avoid ambiguity in case there are
several entities with the same entity id.
attrs: List of attributes to update or to append
append_strict: If `False` the entity attributes are updated (if they
previously exist) or appended (if they don't previously exist)
with the ones in the payload.
If `True` all the attributes in the payload not
previously existing in the entity are appended. In addition
to that, in case some of the attributes in the payload
already exist in the entity, an error is returned.
More precisely this means a strict append procedure.
Returns:
None
"""
url = urljoin(self.base_url, f'v2/entities/{entity_id}/attrs')
headers = self.headers.copy()
params = {}
if entity_type:
params.update({'type': entity_type})
if append_strict:
params.update({'options': 'append'})
entity = ContextEntity(id=entity_id,
type=entity_type)
entity.add_attributes(attrs)
# exclude commands from the send data,
# as they live in the IoTA-agent
excluded_keys = {'id', 'type'}
excluded_keys.update(
entity.get_commands(response_format=PropertyFormat.DICT).keys())
try:
res = self.post(url=url,
headers=headers,
json=entity.dict(exclude=excluded_keys,
exclude_unset=True,
exclude_none=True),
params=params)
if res.ok:
self.logger.info("Entity '%s' successfully "
"updated!", entity.id)
else:
res.raise_for_status()
except requests.RequestException as err:
msg = f"Could not update or append attributes of entity" \
f" {entity.id} !"
self.log_error(err=err, msg=msg)
raise
def update_existing_entity_attributes(
self,
entity_id: str,
entity_type: str,
attrs: List[Union[NamedContextAttribute,
Dict[str, ContextAttribute]]]):
"""
The entity attributes are updated with the ones in the payload.
In addition to that, if one or more attributes in the payload doesn't
exist in the entity, an error is returned. This corresponds to a
'PATcH' request.
Args:
entity_id: Entity id to be updated
entity_type: Entity type, to avoid ambiguity in case there are
several entities with the same entity id.
attrs: List of attributes to update or to append
Returns:
None
"""
url = urljoin(self.base_url, f'v2/entities/{entity_id}/attrs')
headers = self.headers.copy()
params = {"type": entity_type}
entity = ContextEntity(id=entity_id,
type=entity_type)
entity.add_attributes(attrs)
try:
res = self.patch(url=url,
headers=headers,
json=entity.dict(exclude={'id', 'type'},
exclude_unset=True,
exclude_none=True),
params=params)
if res.ok:
self.logger.info("Entity '%s' successfully "
"updated!", entity.id)
else:
res.raise_for_status()
except requests.RequestException as err:
msg = f"Could not update attributes of entity" \
f" {entity.id} !"
self.log_error(err=err, msg=msg)
raise
def replace_entity_attributes(
self,
entity_id: str,
entity_type: str,
attrs: List[Union[NamedContextAttribute,
Dict[str, ContextAttribute]]]):
"""
The attributes previously existing in the entity are removed and
replaced by the ones in the request. This corresponds to a 'PUT'
request.
Args:
entity_id: Entity id to be updated
entity_type: Entity type, to avoid ambiguity in case there are
several entities with the same entity id.
attrs: List of attributes to add to the entity
Returns:
None
"""
url = urljoin(self.base_url, f'v2/entities/{entity_id}/attrs')
headers = self.headers.copy()
params = {}
if entity_type:
params.update({'type': entity_type})
entity = ContextEntity(id=entity_id,
type=entity_type)
entity.add_attributes(attrs)
try:
res = self.put(url=url,
headers=headers,
json=entity.dict(exclude={'id', 'type'},
exclude_unset=True,
exclude_none=True),
params=params)
if res.ok:
self.logger.info("Entity '%s' successfully "
"updated!", entity.id)
else:
res.raise_for_status()
except requests.RequestException as err:
msg = f"Could not replace attribute of entity {entity.id} !"
self.log_error(err=err, msg=msg)
raise
# Attribute operations
def get_attribute(self,
entity_id: str,
attr_name: str,
entity_type: str = None,
metadata: str = None,
response_format = '') -> ContextAttribute:
"""
Retrieves a specified attribute from an entity.
Args:
entity_id: Id of the entity. Example: Bcn_Welt
attr_name: Name of the attribute to be retrieved.
entity_type (Optional): Type of the entity to retrieve
metadata (Optional): A list of metadata names to include in the
response. See "Filtering out attributes and metadata" section
for more detail.
Returns:
The content of the retrieved attribute as ContextAttribute
Raises:
Error
"""
url = urljoin(self.base_url,
f'v2/entities/{entity_id}/attrs/{attr_name}')
headers = self.headers.copy()
params = {}
if entity_type:
params.update({'type': entity_type})
if metadata:
params.update({'metadata': ','.join(metadata)})
try:
res = self.get(url=url, params=params, headers=headers)
if res.ok:
self.logger.debug('Received: %s', res.json())
return ContextAttribute(**res.json())
res.raise_for_status()
except requests.RequestException as err:
msg = f"Could not load attribute '{attr_name}' from entity" \
f"'{entity_id}' "
self.log_error(err=err, msg=msg)
raise
def update_entity_attribute(self,
entity_id: str,
attr: Union[ContextAttribute,
NamedContextAttribute],
*,
entity_type: str = None,
attr_name: str = None,
override_metadata: bool = True):
"""
Updates a specified attribute from an entity.
Args:
attr:
context attribute to update
entity_id:
Id of the entity. Example: Bcn_Welt
entity_type:
Entity type, to avoid ambiguity in case there are
several entities with the same entity id.
override_metadata:
Bool, if set to `True` (default) the metadata will be
overwritten. This is for backwards compatibility reasons.
If `False` the metadata values will be either updated if
already existing or append if not.
See also:
https://fiware-orion.readthedocs.io/en/master/user/metadata.html
"""
headers = self.headers.copy()
if not isinstance(attr, NamedContextAttribute):
assert attr_name is not None, "Missing name for attribute. " \
"attr_name must be present if" \
"attr is of type ContextAttribute"
else:
assert attr_name is None, "Invalid argument attr_name. Do not set " \
"attr_name if attr is of type " \
"NamedContextAttribute"
attr_name = attr.name
url = urljoin(self.base_url,
f'v2/entities/{entity_id}/attrs/{attr_name}')
params = {}
if entity_type:
params.update({'type': entity_type})
# set overrideMetadata option (we assure backwards compatibility here)
if override_metadata:
params.update({'options': 'overrideMetadata'})
try:
res = self.put(url=url,
headers=headers,
params=params,
json=attr.dict(exclude={'name'},
exclude_unset=True,
exclude_none=True))
if res.ok:
self.logger.info("Attribute '%s' of '%s' "
"successfully updated!", attr_name, entity_id)
else:
res.raise_for_status()
except requests.RequestException as err:
msg = f"Could not update attribute '{attr_name}' of entity" \
f"'{entity_id}' "
self.log_error(err=err, msg=msg)
raise
def delete_entity_attribute(self,
entity_id: str,
attr_name: str,
entity_type: str = None) -> None:
"""
Removes a specified attribute from an entity.
Args:
entity_id: Id of the entity.
attr_name: Name of the attribute to be retrieved.
entity_type: Entity type, to avoid ambiguity in case there are
several entities with the same entity id.
Raises:
Error
"""
url = urljoin(self.base_url,
f'v2/entities/{entity_id}/attrs/{attr_name}')
headers = self.headers.copy()
params = {}
if entity_type:
params.update({'type': entity_type})
try:
res = self.delete(url=url, headers=headers)
if res.ok:
self.logger.info("Attribute '%s' of '%s' "
"successfully deleted!", attr_name, entity_id)
else:
res.raise_for_status()
except requests.RequestException as err:
msg = f"Could not delete attribute '{attr_name}' of entity" \
f"'{entity_id}' "
self.log_error(err=err, msg=msg)
raise
# Attribute value operations
def get_attribute_value(self,
entity_id: str,
attr_name: str,
entity_type: str = None) -> Any:
"""
This operation returns the value property with the value of the
attribute.
Args:
entity_id: Id of the entity. Example: Bcn_Welt
attr_name: Name of the attribute to be retrieved.
Example: temperature.
entity_type: Entity type, to avoid ambiguity in case there are
several entities with the same entity id.
Returns:
"""
url = urljoin(self.base_url,
f'v2/entities/{entity_id}/attrs/{attr_name}/value')
headers = self.headers.copy()