ngsildclient.api.client#

Module Attributes

logger

This module contains the definition of the Client class.

Classes

Broker([vendor, version])

Represent a NGSI-LD Context Broker.

Client([hostname, port, port_temporal, ...])

An implementation of the NGSI-LD client API.

class ngsildclient.api.client.Broker(vendor=Vendor.UNKNOWN, version='N/A')[source]#

Bases: object

Represent a NGSI-LD Context Broker.

class ngsildclient.api.client.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: object

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

close()[source]#

Terminates the client.

Closes the underlying Requests.Session.

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

Entity

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

NgsiNotConnectedError

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
raise_for_status(r)[source]#

Raises an exception depending on the API response.

Parameters

r (Response) – Response from the Context Broker

ngsildclient.api.client.logger = <Logger ngsildclient.api.client (INFO)>#

This module contains the definition of the Client class.