ngsildclient.model.entity#

Module Attributes

logger

This module contains the definition of the Entity class.

Classes

Entity()

The main goal of this class is to build, manipulate and represent a NGSI-LD compliant entity.

class ngsildclient.model.entity.Entity(type: str, id: str, *, ctx: list = [CORE_CONTEXT])[source]#
class ngsildclient.model.entity.Entity(id: str, *, ctx: list = [CORE_CONTEXT])

Bases: object

The 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

See also

model.NgsiDict

a custom dictionary that inherits from the native dict and provides primitives to build attributes

api.client.Client

the 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: object

The 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.

Parameters

entity (Entity) – The input Entity

Returns

The output entity

Return type

Entity

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"
        }
    }
}
copy()[source]#

Duplicates the entity

Returns

The new entity

Return type

Entity

classmethod duplicate(entity)[source]#

Duplicate a given entity.

Parameters

entity (Entity) – The input Entity

Returns

The output entity

Return type

Entity

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

Entity

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

Entity

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

Entity

See also

model.constants.SmartDataModels

Example

>>> 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

Entity

See also

model.constants.SmartDataModels

Example

>>> 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

Entity

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

Entity

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

NgsiDict

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

Entity

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"
        }
    }
}
unanchor()[source]#

Remove the anchor.

See also

Entity.anchor

ngsildclient.model.entity.logger = <Logger ngsildclient.model.entity (INFO)>#

This module contains the definition of the Entity class.