Skip to content

Instantly share code, notes, and snippets.

@mvonthron
Last active September 19, 2016 21:48
Show Gist options
  • Save mvonthron/17f974d1fc07f70b382e9bc254267027 to your computer and use it in GitHub Desktop.
Save mvonthron/17f974d1fc07f70b382e9bc254267027 to your computer and use it in GitHub Desktop.

mnubo SmartObjects Python client

Table of Content

1. Introduction

2. At a glance

3. Requirements

4. Installation & Configuration

5. Usage

6. Need help?


#1. Introduction

This package provides a simple Python client to connect to mnubo's SmartObjects platform. It gives access to the most common features of mnubo's REST API. All methods require proper authentication. The MnuboClient object handles authentication under the hood based on the client_id and client_secret arguments.

Methods such as create(), delete(), etc, do not return any value. However if anything is invalid or goes wrong, an exception will be thrown so you know what happened.

#2. At a glance

(optional arguments omitted)

Service Method Summary Example
Owners create(owner) create a new owner simple_workflow.py
update(username, owner) update an existing owner
claim(username, device_id) link an existing object to an existing owner simple_workflow.py
create_update(owners) create or update a batch or owners
delete(username) delete an owner
owner_exists(username) check if an owner exists simple_workflow.py
owners_exist(usernames) check if a list of owners exist
Objects create(object) create a new smart object simple_workflow.py
update(device_id, object) update an existing object
create_update(objects) create or update a batch of objects
delete(device_id) delete an object
object_exists(device_id) check if an object exists simple_workflow.py
objects_exist(device_ids) check if a list of objects exist
Events send(events) send a batch of events tagged with multiple devices
send_from_device(device_id, events) send an event tagged with a specific device simple_workflow.py
event_exists(event_id) check if an event exists
events_exist(event_ids) check if list of events exist
Search search(query) performs a search in the platform with the provided JSON query (MQL) simple_workflow.py
validate_query(query) validates an MQL query simple_workflow.py
get_datasets() retrieves the list of datasets available for this account simple_workflow.py

#3. Requirements

  • Python 2.7
  • libraries: requests, six

#4. Installation & Configuration

From PyPI:

$ pip install mnubo

From the sources:

$ git clone https://github.com/mnubo/smartobjects-python-client.git
$ cd smartobjects-python-client
$ python setup.py install

#5. Usage

Initialize the MnuboClient

from mnubo import MnuboClient

client = MnuboClient('<CLIENT_ID>', '<CLIENT_SECRET>', Environment.Production)

The environment argument can be Environment.Sandbox or Environment.Production and automatically resolves to the right API URL.

Optional arguments:

  • compression_enabled: if True, data sent to the platform is compressed using gzip format. Default: True

Use the Owners service

To create owners on the mnubo SmartObjects platform, please refer to the data modeling guide to format correctly the owner's data structure.

Create an Owner

client.owners.create({
    "username": "[email protected]",
    "x_password": "****************",
    "zip_code": "91125"
})

Mandatory properties: username, x_password

Claim a Smart Object for an Owner

client.owners.claim('[email protected]', 'fermat1901')

Update an Owner

client.owners.update('[email protected]', {
    "zip_code": "94305",    # update of an existing property
    "service_type": "phd"   # creation of a new property
})

Create or update owners in batch

results = client.owners.create_update([
    {"username": "[email protected]", "service_type": "prof"},
    {"username": "[email protected]", "x_password": "*******"}   
])

Mandatory properties: x_username_id (all owners), x_x_password_type (new owners)

Returns a list of Result with the completion status of each operation (and reason of failure if any).

Delete an Owner

client.owners.delete('[email protected]')

Check if an owner exists

>>> client.owners.owner_exists('[email protected]')
True

>>> client.owners.owners_exist(['[email protected]', '[email protected]'])
{'[email protected]': True, '[email protected]': False}

Use the Smart Objects Service

To create smart objects on the mnubo SmartObjects platform, please refer to the data modeling guide to format correctly the smart object's data structure.

Create a Smart Object

client.objects.create({
    "x_device_id": "fermat1901",
    "x_object_type": "calculator",
    "precision": "infinite"
})

Mandatory properties: x_device_id, x_object_type

Update a Smart Object

client.objects.update("fermat1901", {
    "is_valid": True
})

Create or update objects in batch

If an object doesn't exist, it will be created, otherwise it will be updated.

client.objects.create_update([
    {"x_device_id": "fermat1901", "is_valid": False},
    {"x_device_id": "ramanujan1887", "x_object_type": "pie"}
])

Mandatory properties: x_device_id (all objects), x_object_type (new objects)

Returns a list of Result objects with the completion status of each operation (and reason of failure if any).

Delete a Smart Object

client.objects.delete("fermat1901")

Check if an object exists

>>> client.objects.object_exists('fermat1901')
True

>>> client.objects.objects_exist(['fermat1901', 'teleporter'])
{'fermat1901': True, 'teleporter': False}

Use the Event Services

To send events to the mnubo SmartObjects platform, please refer to the data modeling guide to format correctly the event's data structure.

Send an Event

results = client.events.send([
    {"x_object": {"x_device_id": "fermat1901"}, "status": "running"},
    {"x_object": {"x_device_id": "ramanujan1887"}, "ratio": 3.1415}
])

Optional arguments:

  • must_exist: if True, an event referring an unknown object will be rejected (default to False)
  • report_results: if True, a list of EventResult objects will be returned with the status of each operation. If False, nothing will be returned when all events are successfully ingested, but a ValueError exception will be thrown if at least one fail. Default to True.

Send an event tagged with a device

This method allows sending multiple events for a given device without the need of setting the target in the payload.

results = client.events.send_from_device("ramanujan1887", [
    {"ratio": 3.1414},
    {"ratio": 3.1413}
])

Optional arguments:

  • report_results: if True, a list of EventResult objects will be returned with the status of each operation. If False, nothing will be returned when all events are successfully ingested, but a ValueError exception will be thrown if at least one fail. Default to True.

Check if an event already exists

>>> client.events.event_exists(UUID("1ff58794-f0da-4738-8444-68a592de6746"))
True

>>> client.events.events_exist([UUID("1ff58794-f0da-4738-8444-68a592de6746"), uuid.uuid4()])
{UUID("1ff58794-f0da-4738-8444-68a592de6746"): True, UUID("e399afda-3c8b-4a6d-bf9c-c51b846c214d"): False}

Use the Search Services

To send search queries to the mnubo SmartObjects platform, please refer to the Search API documentation to format your queries correctly.

Search Query

resultset = client.search.search({
    "from": "owner",
    "limit": 100,
    "select": [
        {"value": "username"}
    ]
})

This method returns a ResultSet containing the result of the search (columns and rows).

>>> "Got {} results!".format(len(resultset))
Got 2 results!
>>> [row.get("username") for row in resultset]
["[email protected]", "[email protected]"]

Validate a search query

For complex queries, it is recommended to use this feature to reduce errors.

validation_result = client.search.validate_query({
    "fro": "owner",
    "limit": 100,
    "select": [
        {"value": "username"}
    ]
})

This method returns a QueryValidationResult object with the status of the validation and list of errors if any:

>>> validation_result.is_valid
False
>>> validation_result.validation_errors
["a query must have a 'from' field"]

Retrieve namespace datasets

This method allows to retrieve the different datasets available for querying. Result is a map of DataSet objects indexed by the dataset name (owner, object, event, session).

>>> datasets = client.search.get_datasets()
>>> [event.key for event in datasets['event'].fields]
["event_id", "x_object.x_device_id", "timestamp", ...]

#6. Need help?

Reach us at [email protected]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment