ngsildclient#
Functions
|
- class ngsildclient.AsyncClient(hostname='localhost', port=1026, port_temporal=1026, secure=False, useragent='ngsildclient v0.3.2', tenant=None, overwrite=False, ignore_errors=False, proxy=None, custom_auth=None)[source]#
Bases:
objectAn implementation of the NGSI-LD client API.
It allows to connect to a NGSI-LD Context Broker, check the connection and try to identify the vendor. As for now it focuses on the /entities/{entityId} endpoint. Allowed operations are : - create(), update(), upsert() - get(), exists() - delete()
Update() and upsert() operations are not atomic, as they aren’t provided as-is by the API, but require chaining 2 API calls.
When encountering errors the Client throws enriched Exceptions, as NGSI-LD API supports ProblemDetails [IETF RFC 7807].
Example
>>> from ngsildclient import *
>>> # Here we don't build our own NGSI-LD entity, but grab an example from SmartDatamodels >>> farm = Entity.load(SmartDatamodels.SmartAgri.Agrifood.AgriFarm)
>>> # farm.pprint()
>>> # Connect to the Context Broker and upsert the entity >>> # As we don't provide any arguments to the Client constructor >>> # It connects to localhost and default port (without any authentication) >>> with Client() as client: >>> client.upsert(farm)
Create a Client instance to interact with the Context Broker.
The Client allows to retrieve or send entities (model.Entity instances) to the Context Broker. For example, one can retrieve an entity from the Context Broker, modify it (update/delete/add properties), and send it back to the Context Broker.
- Parameters
hostname (str, optional) – the hostname to connect to, by default “localhost”
port (int, optional) – the TCP port to connect to, by default NGSILD_DEFAULT_PORT
secure (bool, optional) – whether to use TLS, by default False
useragent (str, optional) – the User Agent string sent in the HTTP headers, by default UA
tenant (str, optional) – the tenant string in case you make use of multi-tenancy, by default None
overwrite (bool, optional) – if set create() will behave like upsert(), by default False
ignore_errors (bool, optional) – if set tests the connection at init time and raisesan exception if failed, by default False
proxy (str, optional) – proxies all requests to the provided proxy string (for debugging purpose), by default None
See also
api.model.Entity- async bulk_import(filename)[source]#
Upsert all entities from a JSON file.
- Parameters
filename (str) – Points to the JSON input file that contains entities.
- Return type
Union[Entity,dict]
- async count(type=None, q=None, gq=None)[source]#
Return number of entities matching type and/or query string.
Facade method for Entities.count().
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
- Returns
The number of matching entities
- Return type
int
Example
>>> with AsyncClient() as client: >>> await client.count(type="AgriFarm") # match a given type
>>> with AsyncClient() as client: >>> await client.count(type="AgriFarm", query='contactPoint[email]=="wheatfarm@email.com"') # match type and query
- async delete_from_file(filename)[source]#
Delete in the broker all entities present in the JSON file.
- Parameters
filename (str) – Points to the JSON input file that contains entities.
- Return type
Union[Entity,dict]
- async delete_where(type=None, q=None, **kwargs)[source]#
Batch delete entities matching type and/or query string.
- Parameters
etype (str) – The entity’s type
query (str) – The query string (NGSI-LD Query Language)
Example
>>> with AsyncClient() as client: >>> await client.delete_where(type="AgriFarm", query='contactPoint[email]=="wheatfarm@email.com"') # match type and query
- async drop(*types)[source]#
Batch delete entities matching the given type.
- Parameters
type (str) – The entity’s type
Example
>>> with AsyncClient() as client: >>> await client.drop("AgriFarm")
- Return type
None
- async exists(eid)[source]#
Tests if an entity exists.
Facade method for Entities.exists(). If already dealing with an entity instance one can provide the entity itself instead of its id.
- Parameters
eid (Union[EntityId, Entity]) – The entity identifier or the entity instance
- Returns
True if the entity exists
- Return type
bool
- async flush_all()[source]#
Batch delete all entities and remove all contexts.
Example
>>> with AsyncClient() as client: >>> await client.purge()
- Return type
None
- async get(eid, ctx=None, asdict=False, **kwargs)[source]#
Retrieve an entity given its id.
Facade method for Entities.retrieve(). If already dealing with an entity instance one can provide the entity itself instead of its id.
- Parameters
eid (Union[EntityId, Entity]) – The entity identifier or the entity instance
ctx (str) – The context
asdict (bool, optional) – If set (instead of returning an Entity) returns the raw API response (a Python dict that represents the JSON response), by default False
- Returns
The retrieved entity
- Return type
- async purge()[source]#
Batch delete all entities.
Example
>>> with AsyncClient() as client: >>> await client.purge()
- Return type
None
- async query(type=None, q=None, gq=None, ctx=None, limit=100, max=1000000)[source]#
Retrieve entities given its type and/or query string.
Retrieve all entities by sending as many requests as needed, using pagination. Assume data hold in memory. Should not be an issue except for very large datasets.
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
ctx (str) – The context
limit (int) – The number of entities retrieved in each request
- Returns
Retrieved entities matching the given type and/or query string
- Return type
list[Entity]
Example
>>> with AsyncClient() as client: >>> await client.query(type="AgriFarm") # match a given type
>>> with AsyncClient() as client: >>> await client.query(type="AgriFarm", q='contactPoint[email]=="wheatfarm@email.com"') # match type and query
- async query_generator(type=None, q=None, gq=None, ctx=None, limit=100, batch=False)[source]#
Retrieve (as a generator) entities given its type and/or query string.
By returning a generator it allows to process entities on the fly without any risk of exhausting memory.
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
ctx (str) – The context
limit (int) – The number of entities retrieved in each request
- Returns
Retrieved a generator of entities (matching the given type and/or query string)
- Return type
list[Entity]
Example
>>> with AsyncClient() as client: >>> async for entity in await client.query_handle(type="AgriFarm"): print(entity)
- async query_handle(type=None, q=None, gq=None, ctx=None, limit=100, *, callback)[source]#
Apply a callback function on entity of the query result.
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
ctx (str) – The context
limit (int) – The number of entities retrieved in each request
callback (Callable[Entity]) – The function to be called on each entity of the result
Example
>>> with AsyncClient() as client: >>> await client.query_handle(type="AgriFarm", lambda e: print(e))
- Return type
None
- async query_head(type=None, q=None, gq=None, ctx=None, n=5)[source]#
Retrieve entities given its type and/or query string.
Retrieve up to PAGINATION_LIMIT_MAX entities. Use query_all() to retrieve all entities. Use entities.query() to deal with limit and offset on your own.
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
ctx (str) – The context
n (int) – The first n entities to be retrieved
- Returns
Retrieved entities matching the given type and/or query string
- Return type
list[Entity]
Example
>>> with AsyncClient() as client: >>> await client.query(type="AgriFarm") # match a given type
>>> with AsyncClient() as client: >>> await client.query(type="AgriFarm", q='contactPoint[email]=="wheatfarm@email.com"') # match type and query
- class ngsildclient.Client(hostname='localhost', port=1026, port_temporal=1026, secure=False, useragent='ngsildclient v0.3.2', tenant=None, overwrite=False, ignore_errors=False, proxy=None, custom_auth=None)[source]#
Bases:
objectAn implementation of the NGSI-LD client API.
It allows to connect to a NGSI-LD Context Broker, check the connection and try to identify the vendor. As for now it focuses on the /entities/{entityId} endpoint. Allowed operations are : - create(), update(), upsert() - get(), exists() - delete()
Update() and upsert() operations are not atomic, as they aren’t provided as-is by the API, but require chaining 2 API calls.
When encountering errors the Client throws enriched Exceptions, as NGSI-LD API supports ProblemDetails [IETF RFC 7807].
Example
>>> from ngsildclient import *
>>> # Here we don't build our own NGSI-LD entity, but grab an example from SmartDatamodels >>> farm = Entity.load(SmartDatamodels.SmartAgri.Agrifood.AgriFarm)
>>> # farm.pprint()
>>> # Connect to the Context Broker and upsert the entity >>> # As we don't provide any arguments to the Client constructor >>> # It connects to localhost and default port (without any authentication) >>> with Client() as client: >>> client.upsert(farm)
Create a Client instance to interact with the Context Broker.
The Client allows to retrieve or send entities (model.Entity instances) to the Context Broker. For example, one can retrieve an entity from the Context Broker, modify it (update/delete/add properties), and send it back to the Context Broker.
- Parameters
hostname (str, optional) – the hostname to connect to, by default “localhost”
port (int, optional) – the TCP port to connect to, by default NGSILD_DEFAULT_PORT
secure (bool, optional) – whether to use TLS, by default False
useragent (str, optional) – the User Agent string sent in the HTTP headers, by default UA
tenant (str, optional) – the tenant string in case you make use of multi-tenancy, by default None
overwrite (bool, optional) – if set create() will behave like upsert(), by default False
ignore_errors (bool, optional) – if set tests the connection at init time and raises an exception if failed, by default False
proxy (str, optional) – proxies all requests to the provided proxy string (for debugging purpose), by default None
See also
api.model.Entity- bulk_import(filename)[source]#
Upsert all entities from a JSON file.
- Parameters
filename (str) – Points to the JSON input file that contains entities.
- Return type
Union[Entity,dict]
- count(type=None, q=None, gq=None)[source]#
Return number of entities matching type and/or query string.
Facade method for Entities.count().
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
- Returns
The number of matching entities
- Return type
int
Example
>>> with Client() as client: >>> client.count(type="AgriFarm") # match a given type
>>> with Client() as client: >>> client.count(type="AgriFarm", query='contactPoint[email]=="wheatfarm@email.com"') # match type and query
- delete_from_file(filename)[source]#
Delete in the broker all entities present in the JSON file.
- Parameters
filename (str) – Points to the JSON input file that contains entities.
- Return type
Union[Entity,dict]
- delete_where(type=None, q=None, gq=None)[source]#
Batch delete entities matching type and/or query string.
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
Example
>>> with Client() as client: >>> client.delete_where(type="AgriFarm", query='contactPoint[email]=="wheatfarm@email.com"') # match type and query
- drop(*types)[source]#
Batch delete entities matching the given type.
- Parameters
type (str) – The entity’s type
Example
>>> with Client() as client: >>> client.drop("AgriFarm")
- Return type
None
- exists(eid)[source]#
Tests if an entity exists.
Facade method for Entities.exists(). If already dealing with an entity instance one can provide the entity itself instead of its id.
- Parameters
eid (Union[EntityId, Entity]) – The entity identifier or the entity instance
- Returns
True if the entity exists
- Return type
bool
- flush_all()[source]#
Batch delete all entities and remove all contexts.
Example
>>> with Client() as client: >>> client.purge()
- Return type
None
- get(eid, ctx=None, asdict=False, **kwargs)[source]#
Retrieve an entity given its id.
Facade method for Entities.retrieve(). If already dealing with an entity instance one can provide the entity itself instead of its id.
- Parameters
eid (Union[EntityId, Entity]) – The entity identifier or the entity instance
ctx (str) – The context
asdict (bool, optional) – If set (instead of returning an Entity) returns the raw API response (a Python dict that represents the JSON response), by default False
- Returns
The retrieved entity
- Return type
- guess_vendor()[source]#
Try to guess the Context Broker vendor.
According to its own API, by using version or status endpoint.
- Returns
A tuple composed of the Vendor (if identified) and the version.
- Return type
tuple[Vendor, Version]
Example
>>> with Client() as client: >>> print(client.guess_vendor()) (<Vendor.ORIONLD: 'Orion-LD'>, 'post-v0.8.1')
- is_connected(raise_for_disconnected=False)[source]#
Test if connection to Context Broker is established.
Send a valid test request to the Context Broker and expects a result.
- Parameters
raise_for_disconnected (bool, optional) – throw an exception if connection fails (if not set only return False), by default False
- Returns
True if the Context Broker replies
- Return type
bool
- Raises
- purge()[source]#
Batch delete all entities.
Example
>>> with Client() as client: >>> client.purge()
- Return type
None
- query(type=None, q=None, gq=None, ctx=None, limit=100, max=1000000)[source]#
Retrieve entities given its type and/or query string.
Retrieve all entities by sending as many requests as needed, using pagination. Assume data hold in memory. Should not be an issue except for very large datasets.
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
ctx (str) – The context
limit (int) – The number of entities retrieved in each request
- Returns
Retrieved entities matching the given type and/or query string
- Return type
list[Entity]
Example
>>> with Client() as client: >>> client.query(type="AgriFarm") # match a given type
>>> with Client() as client: >>> client.query(type="AgriFarm", q='contactPoint[email]=="wheatfarm@email.com"') # match type and query
- query_generator(type=None, q=None, gq=None, ctx=None, limit=100, batch=False)[source]#
Retrieve (as a generator) entities given its type and/or query string.
By returning a generator it allows to process entities on the fly without any risk of exhausting memory.
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
ctx (str) – The context
limit (int) – The number of entities retrieved in each request
- Returns
Retrieved a generator of entities (matching the given type and/or query string)
- Return type
list[Entity]
Example
>>> with Client() as client: >>> for entity in client.query_handle(type="AgriFarm"): print(entity)
- query_handle(type=None, q=None, gq=None, ctx=None, limit=100, *, callback)[source]#
Apply a callback function on entity of the query result.
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
ctx (str) – The context
limit (int) – The number of entities retrieved in each request
callback (Callable[Entity]) – The function to be called on each entity of the result
Example
>>> with Client() as client: >>> client.query_handle(type="AgriFarm", lambda e: print(e))
- Return type
None
- query_head(type=None, q=None, gq=None, ctx=None, n=5)[source]#
Retrieve entities given its type and/or query string.
Retrieve up to PAGINATION_LIMIT_MAX entities. Use query_all() to retrieve all entities. Use entities.query() to deal with limit and offset on your own.
- Parameters
etype (str) – The entity’s type
q (str) – The query string (NGSI-LD Query Language)
gq (str) – The geoquery string (NGSI-LD Geoquery Language)
ctx (str) – The context
n (int) – The first n entities to be retrieved
- Returns
Retrieved entities matching the given type and/or query string
- Return type
list[Entity]
Example
>>> with Client() as client: >>> client.query(type="AgriFarm") # match a given type
>>> with Client() as client: >>> client.query(type="AgriFarm", q='contactPoint[email]=="wheatfarm@email.com"') # match type and query
- class ngsildclient.Entity(type: str, id: str, *, ctx: list = [CORE_CONTEXT])[source]#
- class ngsildclient.Entity(id: str, *, ctx: list = [CORE_CONTEXT])
Bases:
objectThe main goal of this class is to build, manipulate and represent a NGSI-LD compliant entity.
The preferred constructor allows to create an entity from its NGSI-LD type and identifier (and optionally context), If no context is provided, it defaults to the NGSI-LD Core Context. The identifier can be written using the “long form” : the fully qualified urn string. It can also be shorten : - omit the urn prefix (scheme+nss) - omit the type inside the identifier, assuming the naming convention “urn:ngsi-ld:<type>:<remainder>”
An alternate constructor allows to create an entity by just providing its id (and optionally context). In this case the type is inferred from the fully qualified urn string, assuming the naming convention “urn:ngsi-ld:<type>:<remainder>”.
The load() classmethod allows to load a NGSI-LD entity from a file or remotely through HTTP. For convenience some SmartDataModels examples are made available.
Once initiated, we can build a complete NGSI-LD entity by adding attributes to the NGSI-LD entity. An attribute can be a Property, TemporalProperty, GeoProperty or RelationShip. Methods prop(), tprop(), gprop() and rel() are used to respectively build a Property, TemporalProperty, GeoProperty, and Relationship. Attributes can carry metadatas, such as “observedAt”. Attributes can carry user data.
Nested attributes are supported. Methods prop(), tprop(), gprop() are chainable, allowing to build nested properties.
Dates and Datetimes are ISO8601. Helper functions are provided in the module utils.iso8601. Often a same date (the one when the measure/event happened) is used many times in the entity. When building an entity, the first time a datetime is used it is cached, then can be reused using “Auto”.
Given a NGSI-LD entity, many actions are possible : - access/add/remove/update attributes - access/update/remove values - print the content in the normalized or simplified (aka KeyValues) flavor - save the entity to a file - send it to the NGSI-LD Context Broker for creation/update (use the ngsildclient.api package)
A NGSI-LD entity is backed by a NgsiDict object (a custom dictionary that inherits from the native Python dict). So if for any reasons you’re stuck with the library and cannot achieve to build a NGSI-LD entity that fully matches your target datamodel, it’s always possible to manipulate directly the underlying dictionary.
- Raises
NgsiMissingIdError – The identifier is missing
NgsiMissingTypeError – The type is missing
NgsiMissingContextError – The context is missing
See also
model.NgsiDicta custom dictionary that inherits from the native dict and provides primitives to build attributes
api.client.Clientthe NGSI-LD Context Broker client to interact with a Context Broker
Example
>>> from datetime import datetime >>> from ngsildclient import *
>>> # Create the entity >>> e = Entity("AirQualityObserved", "RZ:Obsv4567")
>>> # Add a temporal property named dateObserved >>> # We could provide a string if preferred (rather than a datetime) >>> e.tprop("dateObserved", datetime(2018, 8, 7, 12))
>>> # Add a property named NO2 with a pollutant concentration value and a metadata to indicate the unit (mg/m3) >>> # The accuracy property is nested >>> e.prop("NO2", 22, unitcode="GP", observedat=Auto).prop("accuracy", 0.95, NESTED)
>>> # Add a relationship towards a POI NGSI-LD Entity >>> e.rel("refPointOfInterest", "PointOfInterest:RZ:MainSquare")
>>> # Pretty-print to standard output >>> e.pprint() { "@context": [ "https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld" ], "id": "urn:ngsi-ld:AirQualityObserved:RZ:Obsv4567", "type": "AirQualityObserved", "dateObserved": { "type": "Property", "value": { "@type": "DateTime", "@value": "2018-08-07T12:00:00Z" } }, "NO2": { "type": "Property", "value": 22, "unitCode": "GP", "observedAt": "2018-08-07T12:00:00Z", "accuracy": { "type": "Property", "value": 0.95 } }, "refPointOfInterest": { "type": "Relationship", "object": "urn:ngsi-ld:PointOfInterest:RZ:MainSquare" } }
>>> # Update a property by overriding it >>> e.prop("dateObserved", iso8601.utcnow())
>>> # Update a value using the dot notation >>> e["NO2.accuracy.value"] = 0.96
>>> # Remove a property >>> e.rm("NO2.accuracy")
- class Settings(autoprefix=True, strict=False, autoescape=True, f_print=<built-in function print>)[source]#
Bases:
objectThe default settings used to build an Entity
- autoprefix: bool = True#
A boolean to enable/disable the automatic insertion of the type into the identifier. Default is enabled.
- f_print()#
print(value, …, sep=’ ‘, end=’n’, file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
- anchor()[source]#
Set an anchor.
Allow to specify that the last property is used as an anchor. Once the anchor property is specified, new properties are attached to the anchor property.
Example
Here an anchor is set at the “availableSpotNumber” property. Hence the “reliability” and “providedBy” properties are attached to (nested in) the “availableSpotNumber” property. Without anchoring, the “reliability” and “providedBy” properties would apply to the entity’s root.
>>> from ngsildclient.model.entity import Entity >>> e = Entity("OffStreetParking", "Downtown1") >>> e.prop("availableSpotNumber", 121, observedat=datetime(2017, 7, 29, 12, 5, 2)).anchor() >>> e.prop("reliability", 0.7).rel("providedBy", "Camera:C1").unanchor() >>> e.pprint() { "@context": [ "http://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld", "http://example.org/ngsi-ld/parking.jsonld" ], "id": "urn:ngsi-ld:OffStreetParking:Downtown1", "type": "OffStreetParking", "availableSpotNumber": { "type": "Property", "value": 121, "observedAt": "2017-07-29T12:05:02Z", "reliability": { "type": "Property", "value": 0.7 }, "providedBy": { "type": "Relationship", "object": "urn:ngsi-ld:Camera:C1" } } }
- classmethod from_dict(payload)[source]#
Create a NGSI-LD entity from a dictionary.
The input dictionary must at least contain the ‘id’, ‘type’ and ‘@context’. This method assumes that the input dictionary matches a valid NGSI-LD structure.
- Parameters
payload (dict) – The given dictionary.
- Returns
The result Entity instance
- Return type
- classmethod from_json(content)[source]#
Create a NGSI-LD entity from JSON content.
The JSON content must at least contain the “id”, “type” and “@context”. This method assumes that the input JSON content matches a valid NGSI-LD structure.
- Parameters
payload (str) – The given JSON content.
- Returns
The result Entity instance
- Return type
- gprop(name, value, nested=False, observedat=None, datasetid=None)[source]#
Build a GeoProperty.
Build a GeoProperty and attach it to the current entity. One can chain prop(),tprop(), gprop(), rel() methods to build nested properties.
- Parameters
name (str) – the property name
value (NgsiGeometry) – the property value
- Returns
The updated entity
- Return type
Entity datasetid
Example
>>> from ngsildclient.model.entity import Entity >>> e = Entity("PointOfInterest", "RZ:MainSquare") >>> e.prop("description", "Beach of RZ") >>> e.gprop("location", (44, -8)) >>> e.pprint() { "@context": [ "https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld" ], "id": "urn:ngsi-ld:PointOfInterest:RZ:MainSquare", "type": "PointOfInterest", "description": { "type": "Property", "value": "Beach of RZ" }, "location": {datasetid "type": "GeoProperty", "value": { "type": "Point", "coordinates": [ -8,datasetid } }
- classmethod load(filename)[source]#
Load an Entity from a JSON file, locally from the filesystem or remotely through HTTP.
For convenience some SmartDataModels examples are made available thanks to the Smart Data Models initiative. You can benefit from autocompletion to navigate inside the available datamodels.
- Parameters
filename (str) – If filename corresponds to an URL, the JSON file is downloaded from HTTP. Else it is retrieved locally from the filesystem.
- Returns
The Entity instance
- Return type
See also
model.constants.SmartDataModelsExample
>>> from ngsildclient import * >>> e = Entity.load(SmartDataModels.SmartCities.Weather.WeatherObserved)
- async classmethod load_async(filename)[source]#
Load an Entity from a JSON file, locally from the filesystem or remotely through HTTP.
For convenience some SmartDataModels examples are made available thanks to the Smart Data Models initiative. You can benefit from autocompletion to navigate inside the available datamodels.
- Parameters
filename (str) – If filename corresponds to an URL, the JSON file is downloaded from HTTP. Else it is retrieved locally from the filesystem.
- Returns
The Entity instance
- Return type
See also
model.constants.SmartDataModelsExample
>>> from ngsildclient import * >>> e = await Entity.load_async(SmartDataModels.SmartCities.Weather.WeatherObserved)
- classmethod load_batch(filename)[source]#
Load a batch of entities from a JSON file.
- Parameters
filename (str) – The input file must contain a JSON array
- Returns
A list of entities
- Return type
List[Entity]
Example
>>> from ngsildclient import * >>> rooms = Entity.load_batch("/tmp/rooms_all.jsonld")
- async classmethod load_batch_async(filename)[source]#
Load a batch of entities from a JSON file.
- Parameters
filename (str) – The input file must contain a JSON array
- Returns
A list of entities
- Return type
List[Entity]
Example
>>> from ngsildclient import * >>> rooms = await Entity.load_batch_async("/tmp/rooms_all.jsonld")
- loc(value: NgsiGeometry, nested: bool = False, observedat: Union[str, datetime] = None, datasetid: str = None) Entity#
A helper method to set the frequently used “location” geoproperty.
entity.loc((44, -8)) is a shorcut for entity.gprop(“location”, (44, -8))
- obs(value: NgsiDate = None, nested: bool = False) Entity#
A helper method to set the frequently used “dateObserved” property.
entity.obs(“2022-01-12T12:54:38Z”) is a shorcut for entity.tprop(“dateObserved”, “2022-01-12T12:54:38Z”)
- pprint(kv=False, *args, **kwargs)[source]#
Pretty-print the entity to the standard ouput.
- Parameters
kv (bool, optional) – KeyValues format (aka simplified representation), by default False
- prop(name, value, nested=False, *, unitcode=None, observedat=None, datasetid=None, userdata={}, escape=False)[source]#
Build a Property.
Build a property and attach it to the current entity. One can chain prop(),tprop(), gprop(), rel() methods to build nested properties.
- Parameters
name (str) – the property name
value (Any) – the property value
observedat (Union[str, datetime], optional) – observetAt metadata, timestamp, ISO8601, UTC, by default Noneself._update_entity(name, property, nested)
userdata (NgsiDict, optional) – a dict or NgsiDict containing user data, i.e. userdata={“reliability”: 0.95}, by default NgsiDict()
escape (bool, optional) – if set escape the string value (useful if contains forbidden characters), by default False
- Returns
The updated entity
- Return type
Example
>>> from ngsildclient.model.entity import Entity >>> e = Entity("AirQualityObserved", "RZ:Obsv4567") >>> e.prop("NO2", 22, unitcode="GP") # basic property {'type': 'Property', 'value': 22, 'unitCode': 'GP'} >>> e.prop("PM10", 18, unitcode="GP").prop("reliability", 0.95) # chain methods to obtain a nested property {'type': 'Property', 'value': 0.95} >>> e.pprint() { "@context": [ "https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld" ], "id": "urn:ngsi-ld:AirQualityObserved:RZ:Obsv4567", "type": "AirQualityObserved", "NO2": { "type": "Property", "value": 22, "unitCode": "GP" }, "PM10": { "type": "Property", "value": 18, "unitCode": "GP", "reliability": { "type": "Property", "value": 0.95 } }
- rel(name, value, nested=False, *, observedat=None, datasetid=None, userdata={})[source]#
Build a Relationship Property.
Build a Relationship Property and attach it to the current entity. One can chain prop(),tprop(), gprop(), rel() methods to build nested properties.
- Parameters
name (str) – the property name
value (str) – the property value
- Returns
The updated entity
- Return type
Example
>>> from ngsildclient.model.entity import Entity >>> e = Entity("AirQualityObserved", "RZ:Obsv4567") >>> e.rel("refPointOfInterest", "PointOfInterest:RZ:MainSquare") >>> e.pprint() { "@context": [ "https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld" ], "id": "urn:ngsi-ld:AirQualityObserved:RZ:Obsv4567", "type": "AirQualityObserved", "refPointOfInterest": { "type": "Relationship", "object": "urn:ngsi-ld:PointOfInterest:RZ:MainSquare" } }
- save(filename, *, indent=2)[source]#
Save the entity to a file.
- Parameters
filename (str) – Name of the output file
indent (int, optional) – identation size (number of spaces), by default 2
- async save_async(filename, *, indent=2)[source]#
Save the entity to a file.
- Parameters
filename (str) – Name of the output file
indent (int, optional) – identation size (number of spaces), by default 2
- classmethod save_batch(entities, filename, *, indent=2)[source]#
Save a batch of entities to a JSON file.
- Parameters
entities (List[Entity]) – Batch of entities to be saved
filename (str) – If filename corresponds to an URL, the JSON file is downloaded from HTTP. Else it is retrieved locally from the filesystem.
Example
>>> from ngsildclient import * >>> rooms = [Entity("Room", "Room1"), Entity("Room", "Room2")] >>> Entity.save_batch(rooms, "/tmp/rooms_all.jsonld")
- async classmethod save_batch_async(entities, filename, *, indent=2)[source]#
Save a batch of entities to a JSON file.
- Parameters
entities (List[Entity]) – Batch of entities to be saved
filename (str) – If filename corresponds to an URL, the JSON file is downloaded from HTTP. Else it is retrieved locally from the filesystem.
Example
>>> from ngsildclient import * >>> rooms = [Entity("Room", "Room1"), Entity("Room", "Room2")] >>> await Entity.save_batch_async(rooms, "/tmp/rooms_all.jsonld")
- to_dict(kv=False)[source]#
Returns the entity as a dictionary.
The returned type is NgsiDict, fully compatible with a native dict.
- Parameters
kv (bool, optional) – KeyValues format (aka simplified representation), by default False
- Returns
The underlying native Python dictionary
- Return type
- to_json(kv=False, *args, **kwargs)[source]#
Returns the entity as JSON.
- Parameters
kv (bool, optional) – KeyValues format (aka simplified representation), by default False
- Returns
The JSON content
- Return type
str
- tprop(name, value=None, nested=False)[source]#
Build a TemporalProperty.
Build a TemporalProperty and attach it to the current entity. One can chain prop(),tprop(), gprop(), rel() methoddatasetids to build nested properties.
- Parameters
name (str) – the property name
value (NgsiDate) – the property value, utcnow() if None
- Returns
The updated entity
- Return type
Example
>>> from datetime import datetime >>> from ngsildclient.model.entity import Entity >>> e = Entity("AirQualityObserved", "RZ:Obsv4567") >>> e.tprop("dateObserved", datetime(2018, 8, 7, 12)) >>> e.pprint() { "@context": [datasetid "https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld" ], "id": "urn:ngsi-ld:AirQualityObserved:RZ:Obsv4567", "type": "AirQualityObserved", "dateObserved": { "type": "Property", "value": { "@type": "DateTime", "@value": "2018-08-07T12:00:00Z" } } }
- exception ngsildclient.NgsiAlreadyExistsError(problemdetails)[source]#
Bases:
NgsiContextBrokerError- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception ngsildclient.NgsiApiError[source]#
Bases:
NgsiError- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception ngsildclient.NgsiContextBrokerError(problemdetails)[source]#
Bases:
NgsiApiError- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception ngsildclient.NgsiError[source]#
Bases:
ExceptionThe NgsiError base exception.
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception ngsildclient.NgsiModelError[source]#
Bases:
NgsiError- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class ngsildclient.OpeningHoursBuilder[source]#
Bases:
objectA helper class that allows to easily build an openingHours property.
Simplified. Support a single open timeslot per day.
Example
>>> from ngsildclient import * >>> builder = OpeningHoursBuilder() >>> openinghours = builder.businessdays("10:00", "17:30").saturday("10:00", "14:00").build() >>> # Add an openingHours property to the entity you're creating >>> library = Entity("Library", "MyLibrary") >>> library.prop("openingHours", openinghours) >>> library.pprint() { "@context": [ "https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld" ], "id": "urn:ngsi-ld:Library:MyLibrary", "type": "Library", "openingHours": { "type": "Property", "value": [ { "opens": "10:00", "closes": "17:30", "dayOfWeek": "Monday" }, { "opens": "10:00", "closes": "17:30", "dayOfWeek": "Tuesday" }, { "opens": "10:00", "closes": "17:30", "dayOfWeek": "Wednesday" }, { "opens": "10:00", "closes": "17:30", "dayOfWeek": "Thursday" }, { "opens": "10:00", "closes": "17:30", "dayOfWeek": "Friday" }, { "opens": "10:00", "closes": "14:00", "dayOfWeek": "Saturday" } ] } }
- class ngsildclient.PostalAddressBuilder[source]#
Bases:
objectA helper class that allows to easily build a PostalAddress property.
Example
>>> from ngsildclient import * >>> builder = PostalAddressBuilder() >>> address = builder.street("C/ La Pereda 14") .locality("Santander") .region("Cantabria") .country("Spain") .build() >>> # Add an address property to the entity you're creating >>> busstop = Entity("PublicTransportStop", "santander:busStop:463") >>> busstop.prop("adress", address) >>> busstop.pprint() { "@context": [ "https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld" ], "id": "urn:ngsi-ld:PublicTransportStop:santander:busStop:463", "type": "PublicTransportStop", "adress": { "type": "Property", "value": { "streetAddress": "C/ La Pereda 14", "addressLocality": "Santander", "addressRegion": "Cantabria", "addressCountry": "Spain" } } }
- ngsildclient.shortuuid(random=False)[source]#
Returns a unique identifier, 22 characters long.
May be useful in some cases to create a unique Entity identifier. The string will be 22 characters long, base64-encoded, with padding characters removed. The encoding uses the urlsafe alphabet with a slightly difference. The dash character (sometimes used as a field separator) is replaced by the tilde character.
- Parameters
random (bool, optional) – if set uses UUID1 else UUID4, by default False
- Returns
A short unique identifier, 22 characters longs.
- Return type
str
Example
>>> from ngsildclient import * >>> crop = Entity("AgriCrop", shortuuid()) >>> crop.pprint() { "@context": [ "https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld" ], "id": "urn:ngsi-ld:AgriCrop:SQiKZZRYRnOYgeojIVz5lA", "type": "AgriCrop" }
Modules
This module defines the NgsiError Exception that will be used as a base for all NGSI exceptions. |
|
Contains helper modules to handle iso8601 dates, URLs, NGSI-LD URNs, and generate short uuids. |