1919
2020from copy import deepcopy
2121from functools import partialmethod
22-
2322from datetime import datetime
2423from typing import (
2524 Sequence ,
3130 Mapping ,
3231 Callable ,
3332)
34-
33+ from multipledispatch import dispatch
3534
3635from ngsildclient .model .ngsidict import NgsiDict
3736from ngsildclient .utils import iso8601 , url
3837from ngsildclient .utils .urn import Urn
3938from ngsildclient .model .exceptions import NgsiMissingIdError , NgsiMissingTypeError , NgsiMissingContextError
40- from ngsildclient .model .constants import CORE_CONTEXT , Rel , NgsiDate , NgsiGeometry
39+ from ngsildclient .model .constants import CORE_CONTEXT , LD_PREFIX , Rel , NgsiDate , NgsiGeometry
4140from ngsildclient .settings import globalsettings
4241
4342logger = logging .getLogger (__name__ )
@@ -185,96 +184,38 @@ class Entity:
185184 >>> e.rm("NO2.accuracy")
186185 """
187186
188- def __init__ (
189- self ,
190- * args : str ,
191- ctx : List = None ,
192- payload : dict = None ,
193- autoprefix : Optional [bool ] = None ,
194- ):
195- """Create a NGSI-LD compliant entity
196-
197- Expected args are : the Entity's type and identifier.
198- Example : Entity("AirQualityObserved", "RZ:Obsv4567")
199- The fully qualified identifier is built following the naming convention : "urn:ngsi-ld:{type}:{id}'.
200- "urn:ngsi-ld:" is added if not specified.
201-
202- Alernatively a single arg is allowed : the fully qualified Entity's identifier.
203- Example : Entity("urn:ngsi-ld:AirQualityObserved:RZ:Obsv4567")
204- Type is inferred from the fully qualified identifier.
205-
206- The default behaviour can be disabled : Entity.globalsettings.autoprefix = False.
207-
208-
209- Parameters
210- ----------
211- type : str
212- entity type
213- id : str
214- entity identifier
215- ctx : list, optional
216- the NGSI-LD context, by default the NGSI-LD Core Context
217-
218- Example
219- -------
220- >>> from ngsildclient.model.entity import Entity
221- >>> e1 = Entity("AirQualityObserved", "urn:ngsi-ld:AirQualityObserved:RZ:Obsv4567") # long form
222- >>> e2 = Entity("AirQualityObserved", "AirQualityObserved:RZ:Obsv4567") # omit scheme + nss
223- >>> e3 = Entity("AirQualityObserved", "RZ:Obsv4567") # omit scheme + nss + type
224- >>> print(e1 == e2 == e3)
225- True
226- >>> e1.pprint()
227- {
228- "@context": [
229- "https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld"
230- ],
231- "id": "urn:ngsi-ld:AirQualityObserved:RZ:Obsv4567",
232- "type": "AirQualityObserved"
233- }
234- """
235- self .root : NgsiDict = None
236- self ._lastprop : NgsiDict = None
187+ @staticmethod
188+ def _build_fully_qualified_id (type : str , id : str ) -> Urn :
189+ if globalsettings .autoprefix :
190+ bare_id = Urn .unprefix (id )
191+ if not bare_id .startswith (f"{ type } :" ):
192+ id = f"{ type } :{ bare_id } "
193+ return Urn .prefix (id )
194+
195+ @dispatch (dict )
196+ def __init__ (self , payload : dict ):
197+ if not payload .get ("id" , None ):
198+ raise NgsiMissingIdError ()
199+ if not payload .get ("type" , None ):
200+ raise NgsiMissingTypeError ()
201+ if not payload .get ("@context" ):
202+ payload ["@context" ] = [CORE_CONTEXT ]
203+ self ._lastprop = self .root = NgsiDict (payload )
237204 self ._anchored : bool = False
238205 self ._lastwasmulti : bool = False
239206
240- if len (args ) == 2 :
241- type , id = args
242- elif len (args ) == 1 :
243- id , type = args [0 ], None
244- elif len (args ) == 0 and payload is not None : # create Entity from a dictionary
245- if not payload .get ("id" , None ):
246- raise NgsiMissingIdError ()
247- if not payload .get ("type" , None ):
248- raise NgsiMissingTypeError ()
249- if not payload .get ("@context" , None ):
250- raise NgsiMissingContextError ()
251- self ._lastprop = self .root = NgsiDict (payload )
252- return
253- else :
254- raise ValueError ("Expecteds args : type, id (alt. fully qualified id)" )
255-
256- if autoprefix is None :
257- autoprefix = globalsettings .autoprefix
258- if not ctx :
259- ctx = [CORE_CONTEXT ]
260-
261- # create a new Entity using its id and type
262- if type is None : # try to infer type from the fully qualified identifier
263- id = Urn .prefix (id )
264- urn = Urn (id )
265- if (type := urn .infertype ()) is None :
266- raise NgsiMissingTypeError (f"{ urn .fqn = } " )
267- else : # type is not None
268- autoprefix &= not Urn .is_prefixed (id )
269- if autoprefix :
270- bareid = Urn .shorten (id )
271- prefix = f"{ type } :"
272- if not bareid .startswith (prefix ):
273- id = prefix + bareid
274- id = Urn .prefix (id ) # set the prefix "urn:ngsi-ld:" if not already done
275- urn = Urn (id )
276-
277- self ._lastprop = self .root = NgsiDict ({"@context" : ctx , "id" : urn .fqn , "type" : type })
207+ @dispatch (str , str )
208+ def __init__ (self , type : str , id : str , * , ctx : List [str ] = None ): # noqa F811
209+ id = Entity ._build_fully_qualified_id (type , id )
210+ self .__init__ ({"id" : id , "type" : type , "@context" : ctx or [CORE_CONTEXT ]})
211+
212+ @dispatch (str )
213+ def __init__ (self , id : str , * , ctx : List [str ] = None ): # noqa F811
214+ id = Urn .prefix (id )
215+ urn = Urn (id )
216+ if (type := urn .infertype ()) is None :
217+ raise NgsiMissingTypeError (f"{ urn .fqn = } " )
218+ self .__init__ ({"id" : id , "type" : type , "@context" : ctx or [CORE_CONTEXT ]})
278219
279220 @classmethod
280221 def from_dict (cls , payload : dict ):
@@ -293,7 +234,7 @@ def from_dict(cls, payload: dict):
293234 Entity
294235 The result Entity instance
295236 """
296- return cls (payload = payload )
237+ return cls (payload )
297238
298239 @classmethod
299240 def from_json (cls , content : str ):
@@ -313,7 +254,7 @@ def from_json(cls, content: str):
313254 The result Entity instance
314255 """
315256 payload : dict = json .loads (content )
316- return cls (payload = payload )
257+ return cls (payload )
317258
318259 @classmethod
319260 def duplicate (cls , entity : Entity ) -> Entity :
0 commit comments