Welcome to helium’s documentation!¶
Contents:
helium package¶
The public interface to the helium-python library.
-
helium.
from_iso_date
(str)¶ Convert an ISO8601 to a datetime.
Parameters: str (string) – The ISO8601 formatted string to convert Returns: A datetime
object representing the given time
-
helium.
to_iso_date
(timestamp)¶ Convert a UTC timestamp to an ISO8601 string.
datetime instances can be constructed in alternate timezones. This function assumes that the given timestamp is in the UTC timezone.
Parameters: timestamp (datetime) – A datetime object in the UTC timezone. Returns: An ISO8601 formatted string representing the timestamp.
-
helium.
build_request_body
(type, id, attributes=None, relationships=None)¶ Build a request body object.
A body JSON object is used for any of the
update
orcreate
methods onResource
subclasses. In normal library use you should not have to use this function directly.Parameters: - type (string) – The resource type for the attribute
- id (uuid) – The id of the object to update. This may be
None
Keyword Arguments: - attributes (dict) – A JSON dictionary of the attributes to set
- relationships (dict) –
Returns: - A valid attribute dictionary. Often used in the
update
or create
Resource`
methods.
-
helium.
build_request_relationship
(type, ids)¶ Build a relationship list.
A relationship list is used to update relationships between two resources. Setting sensors on a label, for example, uses this function to construct the list of sensor ids to pass to the Helium API.
Parameters: - type (string) – The resource type for the ids in the relationship
- ids ([uuid] or uuid) – Just one or a list of resource uuids to use in the relationship
Returns: A ready to use relationship JSON object.
-
helium.
build_request_include
(include, params)¶ Augment request parameters with includes.
When one or all resources are requested an additional set of resources can be requested as part of the request. This function extends the given parameters for a request with a list of resource types passed in as a list of
Resource
subclasses.Parameters: - include ([Resource class]) – A list of resource classes to include
- params (dict) – The (optional) dictionary of request parameters to extend
Returns: An updated or new dictionary of parameters extended with an include query parameter.
-
exception
helium.
Error
(response)¶ Bases:
exceptions.Exception
The base exception class.
-
message
¶ The actual message returned by the API.
-
-
exception
helium.
ServerError
(response)¶ Bases:
helium.exceptions.Error
-
exception
helium.
ClientError
(response)¶ Bases:
helium.exceptions.Error
-
exception
helium.
NotFoundError
(response)¶ Bases:
helium.exceptions.Error
-
class
helium.
Base
(json)¶ Bases:
object
A base class to deal with json based attributes.
The base class stores a given json object and dynamically promotes requested object attributes from the cached jason data if they exist.
Sub-classes can override methods to promote attribtues on construction or lazily, when they’re requested
-
class
helium.
Resource
(json, session, include=None, included=None)¶ Bases:
helium.resource.Base
The base class for all Helium resources.
The Helium API uses JSONAPI extensively. The
Resource
object provides a number of useful JSONAPI abstractions.A resource will at least have an
id
attribute, which is promoted from the underlying json data on creation.A resource can be requested to include relation resources in its response using the include request parameter. The
include
argument allows relationship lookups to validate whether the relationship was originally requested. You normally don’t need to specify this since the Resource retrieval methods likeall
andfind
take care of this behavior.-
classmethod
all
(session, include=None)¶ Get all resources of the given resource class.
This should be called on sub-classes only.
The include argument allows relationship fetches to be optimized by including the target resources in the request of the containing resource. For example:
.. code-block:: python
org = Organization.singleton(session, include=[Sensor]) org.sensors(use_included=True)Will fetch the sensors for the authorized organization as part of retrieving the organization. The
use_included
forces the use of included resources and avoids making a separate request to get the sensors for the organization.Parameters: session (Session) – The session to look up the resources in Keyword Arguments: incldue – A list of resource classes to include in the request. Returns: - An iterator over all the resources of
- this type
Return type: iterable(Resource)
-
classmethod
create
(session, attributes=None, relationships=None)¶ Create a resource of the resource.
This should only be called from sub-classes
Parameters: - session (Session) – The session to create the resource in.
- attributes (dict) – Any attributes that are valid for the given resource type.
- relationships (dict) – Any relationships that are valid for the given resource type.
Returns: An instance of a resource.
Return type:
-
delete
()¶ Delete the resource.
Returns: True if the delete is successful. Will throw an error if other errors occur
-
classmethod
find
(session, resource_id, include=None)¶ Retrieve a single resource.
This should only be called from sub-classes.
Parameters: - session (Session) – The session to find the resource in
- resource_id – The
id
for the resource to look up
Keyword Arguments: include – Resource classes to include
Returns: - An instance of a resource, or throws a
NotFoundError
if the resource can not be found.
Return type:
-
is_singleton
()¶ Whether this instance is a singleton.
-
classmethod
singleton
(session, include=None)¶ Get the a singleton API resource.
Some Helium API resources are singletons. The authorized user and organization for a given API key are examples of this.
authorized_user = User.singleton(session)
will retrieve the authorized user for the given
Session
Keyword Arguments: include – Resource classes to include
-
update
(attributes=None)¶ Update this resource.
Not all aspects of a resource can be updated. If the server rejects updates an error will be thrown.
Keyword Arguments: attributes (dict) – Attributes that are to be updated Returns: A new instance of this type of resource with the updated attribute. On errors an exception is thrown. Return type: Resource
-
classmethod
where
(session, include=None, metadata=None, filter=None)¶ Get filtered resources of the given resource class.
This should be called on sub-classes only.
The include argument allows relationship fetches to be optimized by including the target resources in the request of the containing resource. For example:
.. code-block:: python
org = Organization.singleton(session, include=[Sensor]) org.sensors(use_included=True)Will fetch the sensors for the authorized organization as part of retrieving the organization. The
use_included
forces the use of included resources and avoids making a separate request to get the sensors for the organization.The metadata argument enables filtering on resources that support metadata filters. For example:
.. code-block:: python
sensors = Sensor.where(session, metadata={ ‘asset_id’: ‘23456’ })Will fetch all sensors that match the given metadata attribute.
The filter argument enables filtering the resulting resources based on a passed in function. For example:
.. code-block::python
sensors = Sensor.where(session, filter=lambda s: s.name.startswith(“a”))Will fetch all sensors and apply the given filter to only return sensors who’s name start with the given string.
Parameters: session (Session) – The session to look up the resources in
Keyword Arguments: - incldue (list) – The resource classes to include in the request.
- metadata (dict or list) – The metadata filter to apply
Returns: - An iterator over all found resources
of this type
Return type: iterable(Resource)
-
classmethod
-
class
helium.
ResourceMeta
(json)¶ Bases:
helium.resource.Base
Meta information for a resource.
Every
Resource
object in the Helium API has an associated meta object that represents system information for the given resource.Most of this information is specific to the given resource, but all meta instances have at least a
created
andupdated
attribute which are timestamps of when the resource was created and last updated, respectively. These timestamps are in ISO8601 format. To convert them to datetime`s use the `from_iso_date utility function.
-
class
helium.
RelationType
¶ Bases:
object
Defines the way a relationship is fetched.
The Helium API does not require an include directive to also mean a full URL relationship. This means that for some relationships you use the URL where for others you use an
include
paramater to get the related objects.For example:
https://api.helium.com/v1/label/<id>/sensor https://api.helium.com/v1/label/<id>?include=sensor
The constants in this class define how the relationship functions should be looked up.
-
DIRECT
= 'direct'¶
-
INCLUDE
= 'include'¶
-
-
helium.
to_one
(dest_class, type='direct', resource_classes=None, reverse=None, reverse_type='direct', writable=False)¶ Create a one to one relation to a given target
Resource
.Parameters: dest_class (Resource) – The target class for the relationship
Keyword Arguments: - type (RelationType) – The relationship approach to use.
- reverse (to_may or to_one) – An optional reverse relationship.
- reverse_type (RelationType) – The reverse relationship approach.
- resource_classes (Resource) – The kinds of Resources to expect in the relationship
Returns: A builder function which, given a source class creates a one-to-one relationship with the target
A one to one relationship means that you can get the associated target object from the object on which the
to_one
was declared.@to_one(Organization) def User(Resource): pass
Declares that a User is associated with one Organization. The decorator automatically adds a method to fetch the associated organization:
org = user.organization()
-
helium.
to_many
(dest_class, type='direct', reverse=None, reverse_type='direct', resource_classes=None, writable=False)¶ Create a one to many relation to a given target
Resource
.Parameters: dest_class (Resource) – The target class for the relationship
Keyword Arguments: - type (RelationType) – The relationship approach to use.
- writable (bool) – Whether the relationship is mutable.
- reverse (to_may or to_one) – An optional reverse relationship.
- reverse_type (RelationType) – The reverse relationship approach.
- resource_classes (Resource) – The kinds of Resources to expect in the relationship
Returns: A builder function which, given a source class creates a one-to-many relationship with the previously supplied target.
A to-many relationship means that the there are many dest_class resources associated with the given source class. The returned method builder will automatically create methods for fetching the associated objects. If the reverse function is supplied the builder will create the correponding reverse relationship methods on the target class.
@to_many(Sensor, writable=True) class Label: pass # find a label, then fetch sensors sensor = label.sensors()
Since the example above also declares that the relationship is writable you can also add, remove and update all target resources from the source object:
# fetch a couple of sensors then add them to the label label.add_sensors([sensor1, sensor2]) # remove a sensor from the label label.remove_sensors([sensor1]) # remove all sensors from the label label.update_sensors([])
-
class
helium.
Session
(adapter=None, api_token=None, base_url=u'https://api.helium.com/v1')¶ Bases:
object
Manages a session with Helium Service.
A session with the Helium service. A session is mostly a front for an underlying adapter that implements the details of requesting and handling the responses. Using the adapters allows the use of different syncrhonous and asynchronous approaches. The default adapter is a synchronous requests based adapter.
-
api_token
¶ The API token for to use for this session.
-
datapoints
(timeseries)¶
-
delete
(url, callback, json=None)¶ Delete a URL.
Parameters: - url (string) – URL for the request
- callback (func) – The response callback function
Keyword Arguments: json (dict) – JSON body for the request
Returns: - The result of the callback handling the resopnse from the
executed request
-
get
(url, callback, params=None, json=None, headers=None)¶ Get a URL.
Parameters: callback (func) – The response callback function
Keyword Arguments: - params (dict) – Parameters for the request
- json (dict) – JSON body for the request
- headers (dict) – Additional headers for the request
Returns: - The result of the callback handling the resopnse from the
executed request
-
live
(url, resource_class, resource_args, params=None)¶ Get a live endpoint.
Parameters: - url (string) – URL for the request
- resource_class (class) – The class to use for entries coming from the live endpoint.
- resource_args (dict) – Additional arguments to pass to the resource_class constructor
Keyword Arguments: params (dict) – Request parameters for the live url
Returns: - An iterator over the live endpoint. Depending on the
adapter the iterator will allow asynchronous behavior. The default adapter will block while iterating over the response of this method.
-
patch
(url, callback, params=None, json=None, headers=None)¶ Patch a URL.
Parameters: - url (string) – URL for the request
- callback (func) – The response callback function
- headers (dict) – HTTP headers for the request
Keyword Arguments: - params (dict) – Parameters for the request
- json (dict) – JSON body for the request
Returns: - The result of the callback handling the resopnse from the
executed request
-
post
(url, callback, params=None, json=None, headers=None, files=None)¶ Post to a URL.
Parameters: - url (string) – URL for the request
- callback (func) – The response callback function
- headers (dict) – HTTP headers for the request
Keyword Arguments: - params (dict) – Parameters for the request
- json (dict) – JSON body for the request
Returns: - The result of the callback handling the resopnse from the
executed request
-
put
(url, callback, params=None, json=None, headers=None)¶ Put to a URL.
Parameters: - url (string) – URL for the request
- callback (func) – The response callback function
Keyword Arguments: - params (dict) – Parameters for the request
- json (dict) – JSON body for the request
- headers (dict) – HTTP headers for the request
Returns: - The result of the callback handling the resopnse from the
executed request
-
-
class
helium.
CB
¶ Bases:
object
Convenience callback functions for sessions.
This class offers up convenience callback builders that make it easy to use the callback session API to behave like a synchronous API.
-
classmethod
boolean
(true_code, false_code=None)¶ Callback to validate a response code.
The returned callback checks whether a given response has a
status_code
that is considered good (true_code
) and raise an appropriate error if not.The optional
false_code
allows for a non-successful status code to return False instead of throwing an error. This is used, for example in relationship mutation to indicate that the relationship was not modified.Parameters: true_code (int) – The http status code to consider as a success Keyword Arguments: false_code (int) – The http status code to consider a failure Returns: - A function that given a response returns
True
if the - response’s status code matches the given code. Raises
a
HeliumError
if the response code does not match.
- A function that given a response returns
-
classmethod
json
(status_code, process)¶ Callback to validate and extract a JSON object.
The returned callback checks a given response for the given status_code using :function:`response_boolean`. On success the response JSON is parsed and returned.
Parameters: status_code (int) – The http status code to consider a success Returns: - A function that given a response returns the JSON object
- in the given response. Raises a
HeliumError
if the response code does not match.
-
classmethod
-
class
helium.
Organization
(json, session, include=None, included=None)¶ Bases:
helium.resource.Resource
The top level owner of resources.
An organization represents container for all the sensors, elements and labels that you own.
All
User
resources in an organization have access to all resources in an organization.-
elements
(use_included=False, filter=None)¶ Fetch the elements associated with this
Organization
.Returns: The elements of Organization
Return type: iterable(Element)
-
labels
(use_included=False, filter=None)¶ Fetch the labels associated with this
Organization
.Returns: The labels of Organization
Return type: iterable(Label)
-
metadata
()¶ Fetch the metadata for this
Organization
.Returns: The Metadata
for thisOrganization
-
sensors
(use_included=False, filter=None)¶ Fetch the sensors associated with this
Organization
.Returns: The sensors of Organization
Return type: iterable(Sensor)
-
timeseries
(**kwargs)¶ Fetch the timeseries for this
Organization
.Returns: The Timeseries
for thisOrganization
Keyword Arguments: **kwargs – The Timeseries
object constructor arguments.
-
users
(use_included=False, filter=None)¶ Fetch the users associated with this
Organization
.Returns: The users of Organization
Return type: iterable(User)
-
-
class
helium.
User
(json, session, include=None, included=None)¶ Bases:
helium.resource.Resource
An authorized user of the Helium API.
A user represents a single developer using the Helium API. Each user gets their own API key, which gives them access to all the resources in the
Organization
that the user belongs to.
-
class
helium.
Timeseries
(session, resource_class, resource_id, datapoint_class=<class 'helium.timeseries.DataPoint'>, datapoint_id=None, page_size=None, direction=u'prev', start=None, end=None, agg_size=None, agg_type=None, port=None)¶ Bases:
_abcoll.Iterable
A timeseries readings container.
Instances of this class represents a single timeseries query. A timeseries will automatically page forward or backward through the pages returned from the Helium API to return data points that fit within the given arguments.
The timeseries instance is an
Iterable
which can be used to lazily iterate over very large timeseries data sets. The returned timeseries object will not actually start making any requests to the Helium API until you start iterating over it.For example, given:
@timeseries() class Sensor(Resource): pass
You can request a timeseries using:
# Fetch a sensor timeseries = sensor.timeseries() # Get the first 10 readings first10 = timeseries.take(10)
Note that each call to
sensor.timeseries()
will return a new timeseries object which you can iterate over.You can filter timeseries data by specifying
port
,start
orend
dates. Note that start and end dates support a relaxed form of ISO8601:timeseries = sensor.timeseries(start='2016-09-01', end='2016-04-07T19:12:06Z')
You can aggregate numeric timeseries data by specifying
agg_type
andagg_size
. For example, to aggregate minimum, maximum and average temperature readings in 6 hour buckets:timeseries = sensor.timeseries(agg_type='min,max,avg', agg_size='6h', port='t')
The resulting data points will have an aggregate value that will contain the requested aggregates as attributes:
first = list(islice(timeseries, 1))[0] print(first.value.min)
-
create
(port, value, timestamp=None)¶ Post a new reading to a timeseries.
A reading is comprised of a port, a value and a timestamp.
A port is like a tag for the given reading and gives an indication of the meaning of the value.
The value of the reading can be any valid json value.
The timestamp is considered the time the reading was taken, as opposed to the created time of the data-point which represents when the data-point was stored in the Helium API. If the timestamp is not given the server will construct a timestemp upon receiving the new reading.
Parameters: - port (string) – The port to use for the new data-point
- value – The value for the new data-point
Keyword Arguments: timestamp (
datetime
) – An optionaldatetime
object
-
live
()¶ Get a live stream of timeseries readings.
This returns an Iterable over a live stream of readings. Note that the result will need to be closed since the system can not tell when you’ll be done with it.
You can either call
close
on the endpoint when you’re or use the context management facilities of the endpoint.# Fetch a sensor timeseries = sensor.timeseries() # ensure live endpoint closed with timeseries.live() as live: # Wait for 10 readings first10 = list(islice(live, 10))
Returns:
-
take
(n)¶ Return the next n datapoints.
Parameters: n (int) – The number of datapoints to retrieve Returns: A list of at most n datapoints.
-
-
class
helium.
DataPoint
(json, session, **kwargs)¶ Bases:
helium.resource.Resource
Data points for timeseries.
-
sensor_id
¶ The id of the sensor of this data point.
Returns: The id of the sensor that generated this datapoint. Will throw an AttributeError if no sensor id was found in the underlyign data.
-
-
helium.
timeseries
()¶ Create a timeseries builder.
Returns: A builder function which, given a class creates a timeseries relationship for that class.
-
helium.
AggregateValue
¶ alias of
agg
-
class
helium.
DeviceConfiguration
(json, session, include=None, included=None)¶ Bases:
helium.resource.Resource
Association between a device and a configuration.
A device configuration is the association between a device and a Configuration.
-
configuration
(use_included=False)¶ Fetch the configuration associated with this
DeviceConfiguration
.Returns: The Configuration
of thisDeviceConfiguration
Return type: Configuration
-
classmethod
create
(session, device=None, configuration=None, **kwargs)¶ Create a device configuration.
Create a device configuration with the given device and configuration.
Parameters: session (Session) – The session to use for the request
Keyword Arguments: - device (Device) – The device to configure, such as an Element or a Sensor
- configuration (Configuration) – The configuration to apply to the device.
Returns: The created device configuration. Throws an exception if any failure occurs.
-
device
(use_included=False)¶ Fetch the device associated with this
DeviceConfiguration
.Returns: The Device
of thisDeviceConfiguration
Return type: Device
-
is_loaded
()¶ Check is a device configuration is loaded.
Returns: True if the device configuration was loaded by Helium, False if the device configuraiton is still pending.``
-
-
class
helium.
Configuration
(json, session, include=None, included=None)¶ Bases:
helium.resource.Resource
Configuration holder.
Helium devices are configurable. This resource holds those attributes. Configuration are not mutable for performance auditability purposes. In order to update a configuration you will need to create a new one and associate the new one with the device you’re configuration.
In order to apply a configuration to a device, use a DeviceConfiguration.
For example to configure a sensor that takes a
min
andmax
valueconfig = Configuration(client, attributes={ 'min': 0, 'max': 100 }) device_config = DeviceConfiguration.create(client, device=sensor, configuration=config)
Once the device configuration is created it is in a
pending
state until the system loads it for delivery to the given device. At any given time a device can have at most one pending and one loaded configuration.Note that a created configuration can be applied to multiple devices by creating multiple device configurations.
-
device_configurations
(use_included=False, filter=None)¶ Fetch the device_configurations associated with this
Configuration
.Returns: The device_configurations of Configuration
Return type: iterable(DeviceConfiguration)
-
-
class
helium.
Device
(json, session, include=None, included=None)¶ Bases:
helium.resource.Resource
Common behavior for devices.
Devices are physical resources that share common behavior such as DeviceConfiguration
-
device_configuration
(pending=False, use_included=False)¶ Get a specific device configuration.
A device can have at most one loaded and one pending device configuration. This returns that device_configuration based on a given flag.
Keyword Arguments: - pending (bool) – Fetch the pending configuration or return the loaded one.
- use_included (bool) – Use included resources in this device configuration.
Returns: The requested loaded or pending configuration or None if no device configuration is found.
-
device_configurations
(use_included=False, filter=None)¶ Fetch the device_configurations associated with this
Device
.Returns: The device_configurations of Device
Return type: iterable(DeviceConfiguration)
-
-
class
helium.
Sensor
(json, session, include=None, included=None)¶ Bases:
helium.device.Device
-
element
(use_included=False)¶ Fetch the element associated with this
Sensor
.Returns: The Element
of thisSensor
Return type: Element
-
labels
(use_included=False, filter=None)¶ Fetch the labels associated with this
Sensor
.Returns: The labels of Sensor
Return type: iterable(Label)
-
timeseries
(**kwargs)¶ Fetch the timeseries for this
Sensor
.Returns: The Timeseries
for thisSensor
Keyword Arguments: **kwargs – The Timeseries
object constructor arguments.
-
-
class
helium.
Metadata
(json, session, target_resource_path)¶ Bases:
helium.resource.Resource
Arbitrary JSON store for resources.
When a
Resource
declares a Metadata relationship:The corresponding resource has a
metadata
method to fetch a metadata object. This metadata object is an arbitrary store for JSON data that can be updated or replaced.Updating the metadata means adding or changing existing attributes in the JSON object.
Replacing the metadata replaces the entire JSON object with the given value.
-
replace
(attributes)¶ Replace the metadata.
Replaces this metadata with the given attributes, removing all other attribute known to the Helium API for this metadata.
Keyword Arguments: attributes (dict) – A dictionary that can be represented as JSON. Returns: The replaced metadata
-
update
(attributes)¶ Update metadata.
Updates this metadata with the given attributes. Updating means that the given attributes are updated or added to the existing metadata instance.
Keyword Arguments: attributes (dict) – A dictionary that can be represented as JSON. Returns: The updated metadata
-
-
helium.
metadata
()¶ Create a metadata method builder.
Returns: A builder function that, given a class, creates a metadata relationship for that class.
-
class
helium.
Element
(json, session, include=None, included=None)¶ Bases:
helium.device.Device
-
labels
(use_included=False, filter=None)¶ Fetch the labels associated with this
Element
.Returns: The labels of Element
Return type: iterable(Label)
-
sensors
(use_included=False, filter=None)¶ Fetch the sensors associated with this
Element
.Returns: The sensors of Element
Return type: iterable(Sensor)
-
timeseries
(**kwargs)¶ Fetch the timeseries for this
Element
.Returns: The Timeseries
for thisElement
Keyword Arguments: **kwargs – The Timeseries
object constructor arguments.
-
-
class
helium.
Label
(json, session, include=None, included=None)¶ Bases:
helium.resource.Resource
-
add_elements
(resources)¶ Add elements to this
Label
.Parameters: resources – A list of Element
to addReturns: True if the relationship was mutated, False otherwise
-
add_sensors
(resources)¶ Add sensors to this
Label
.Parameters: resources – A list of Sensor
to addReturns: True if the relationship was mutated, False otherwise
-
classmethod
create
(session, attributes=None, sensors=None, elements=None, **kwargs)¶
-
elements
(use_included=False, filter=None)¶ Fetch the elements associated with this
Label
.Returns: The elements of Label
Return type: iterable(Element)
-
remove_elements
(resources)¶ Remove elements from this
Label
.Parameters: resources – A list of Element
to removeReturns: True if the relationship was mutated, False otherwise
-
remove_sensors
(resources)¶ Remove sensors from this
Label
.Parameters: resources – A list of Sensor
to removeReturns: True if the relationship was mutated, False otherwise
-
sensors
(use_included=False, filter=None)¶ Fetch the sensors associated with this
Label
.Returns: The sensors of Label
Return type: iterable(Sensor)
-
timeseries
(**kwargs)¶ Fetch the timeseries for this
Label
.Returns: The Timeseries
for thisLabel
Keyword Arguments: **kwargs – The Timeseries
object constructor arguments.
-
-
class
helium.
Client
(adapter=None, api_token=None, base_url=u'https://api.helium.com/v1')¶ Bases:
helium.session.Session
Construct a client to the Helium API.
The Client offers up methods to retrieve the “roots” of Helium resources such as sensors and label.
Once resources are retrieved they are attached to the client that constructed them and handle further requests independently.
Get the authorized organization.
Returns: The organization for the authorized API key Return type: Organization
Get the authorized user.
Returns: The user for the authorized API key Return type: User
-
label
(label_id)¶ Find a single label.
Parameters: label_id (str) – The UUID of the label to look up Returns: A label resource Return type: Label
-
labels
()¶ Iterate over all labels.
Returns: An iterable over labels for the authorized API key Return type: iterable(Label)
Subpackages¶
helium.adapter package¶
A module for adapting Helium Sessions.
Submodules¶
helium.adapter.aiohttp module¶
helium.adapter.requests module¶
An adapter for the standard blocking requests library.
-
class
helium.adapter.requests.
Adapter
¶ Bases:
requests.sessions.Session
A synchronous adapter based on the requests library.
-
api_token
¶ The API token to use.
-
datapoints
(timeseries)¶
-
delete
(url, callback, json=None)¶
-
get
(url, callback, params=None, json=None, headers=None)¶
-
live
(session, url, resource_class, resource_args, params=None)¶
-
patch
(url, callback, params=None, json=None, headers=None)¶
-
post
(url, callback, params=None, json=None, headers=None, files=None)¶
-
put
(url, callback, params=None, json=None, headers=None)¶
-
take
(iter, n)¶
-
-
class
helium.adapter.requests.
DatapointIterator
(timeseries)¶ Bases:
_abcoll.Iterator
Iterator over a timeseries endpoint.
-
next
()¶ Python 2 iterator compatibility.
-
-
class
helium.adapter.requests.
LiveIterator
(response, session, resource_class, resource_args)¶ Bases:
_abcoll.Iterable
Iterable over a live endpoint.
-
close
()¶ Close the live session.
-
take
(n)¶ Return the next n datapoints.
Parameters: n (int) – The number of datapoints to retrieve Returns: A list of at most n datapoints.
-
Submodules¶
helium.client module¶
The Helium Client.
-
class
helium.client.
Client
(adapter=None, api_token=None, base_url=u'https://api.helium.com/v1')¶ Bases:
helium.session.Session
Construct a client to the Helium API.
The Client offers up methods to retrieve the “roots” of Helium resources such as sensors and label.
Once resources are retrieved they are attached to the client that constructed them and handle further requests independently.
Get the authorized organization.
Returns: The organization for the authorized API key Return type: Organization
Get the authorized user.
Returns: The user for the authorized API key Return type: User
-
label
(label_id)¶ Find a single label.
Parameters: label_id (str) – The UUID of the label to look up Returns: A label resource Return type: Label
-
labels
()¶ Iterate over all labels.
Returns: An iterable over labels for the authorized API key Return type: iterable(Label)
helium.element module¶
The element resource.
-
class
helium.element.
Element
(json, session, include=None, included=None)¶ Bases:
helium.device.Device
-
labels
(use_included=False, filter=None)¶ Fetch the labels associated with this
Element
.Returns: The labels of Element
Return type: iterable(Label)
-
helium.exceptions module¶
Exceptions for the Helium API library.
-
exception
helium.exceptions.
ClientError
(response)¶ Bases:
helium.exceptions.Error
-
exception
helium.exceptions.
Error
(response)¶ Bases:
exceptions.Exception
The base exception class.
-
message
¶ The actual message returned by the API.
-
-
exception
helium.exceptions.
NotFoundError
(response)¶ Bases:
helium.exceptions.Error
-
exception
helium.exceptions.
ServerError
(response)¶ Bases:
helium.exceptions.Error
-
helium.exceptions.
error_for
(response)¶ Return the appropriate initialized exception class for a response.
helium.label module¶
The label resource.
-
class
helium.label.
Label
(json, session, include=None, included=None)¶ Bases:
helium.resource.Resource
-
add_elements
(resources)¶ Add elements to this
Label
.Parameters: resources – A list of Element
to addReturns: True if the relationship was mutated, False otherwise
-
add_sensors
(resources)¶ Add sensors to this
Label
.Parameters: resources – A list of Sensor
to addReturns: True if the relationship was mutated, False otherwise
-
classmethod
create
(session, attributes=None, sensors=None, elements=None, **kwargs)¶
-
elements
(use_included=False, filter=None)¶ Fetch the elements associated with this
Label
.Returns: The elements of Label
Return type: iterable(Element)
-
remove_elements
(resources)¶ Remove elements from this
Label
.Parameters: resources – A list of Element
to removeReturns: True if the relationship was mutated, False otherwise
-
remove_sensors
(resources)¶ Remove sensors from this
Label
.Parameters: resources – A list of Sensor
to removeReturns: True if the relationship was mutated, False otherwise
-
sensors
(use_included=False, filter=None)¶ Fetch the sensors associated with this
Label
.Returns: The sensors of Label
Return type: iterable(Sensor)
-
timeseries
(**kwargs)¶ Fetch the timeseries for this
Label
.Returns: The Timeseries
for thisLabel
Keyword Arguments: **kwargs – The Timeseries
object constructor arguments.
-
helium.metadata module¶
The metadata resource.
-
class
helium.metadata.
Metadata
(json, session, target_resource_path)¶ Bases:
helium.resource.Resource
Arbitrary JSON store for resources.
When a
Resource
declares a Metadata relationship:The corresponding resource has a
metadata
method to fetch a metadata object. This metadata object is an arbitrary store for JSON data that can be updated or replaced.Updating the metadata means adding or changing existing attributes in the JSON object.
Replacing the metadata replaces the entire JSON object with the given value.
-
replace
(attributes)¶ Replace the metadata.
Replaces this metadata with the given attributes, removing all other attribute known to the Helium API for this metadata.
Keyword Arguments: attributes (dict) – A dictionary that can be represented as JSON. Returns: The replaced metadata
-
update
(attributes)¶ Update metadata.
Updates this metadata with the given attributes. Updating means that the given attributes are updated or added to the existing metadata instance.
Keyword Arguments: attributes (dict) – A dictionary that can be represented as JSON. Returns: The updated metadata
-
-
helium.metadata.
metadata
()¶ Create a metadata method builder.
Returns: A builder function that, given a class, creates a metadata relationship for that class.
helium.organization module¶
The organization resource.
-
class
helium.organization.
Organization
(json, session, include=None, included=None)¶ Bases:
helium.resource.Resource
The top level owner of resources.
An organization represents container for all the sensors, elements and labels that you own.
All
User
resources in an organization have access to all resources in an organization.-
elements
(use_included=False, filter=None)¶ Fetch the elements associated with this
Organization
.Returns: The elements of Organization
Return type: iterable(Element)
-
labels
(use_included=False, filter=None)¶ Fetch the labels associated with this
Organization
.Returns: The labels of Organization
Return type: iterable(Label)
-
metadata
()¶ Fetch the metadata for this
Organization
.Returns: The Metadata
for thisOrganization
-
sensors
(use_included=False, filter=None)¶ Fetch the sensors associated with this
Organization
.Returns: The sensors of Organization
Return type: iterable(Sensor)
-
timeseries
(**kwargs)¶ Fetch the timeseries for this
Organization
.Returns: The Timeseries
for thisOrganization
Keyword Arguments: **kwargs – The Timeseries
object constructor arguments.
-
users
(use_included=False, filter=None)¶ Fetch the users associated with this
Organization
.Returns: The users of Organization
Return type: iterable(User)
-
helium.relations module¶
Manage relationships between resources.
-
class
helium.relations.
RelationType
¶ Bases:
object
Defines the way a relationship is fetched.
The Helium API does not require an include directive to also mean a full URL relationship. This means that for some relationships you use the URL where for others you use an
include
paramater to get the related objects.For example:
https://api.helium.com/v1/label/<id>/sensor https://api.helium.com/v1/label/<id>?include=sensor
The constants in this class define how the relationship functions should be looked up.
-
DIRECT
= 'direct'¶
-
INCLUDE
= 'include'¶
-
-
helium.relations.
to_many
(dest_class, type='direct', reverse=None, reverse_type='direct', resource_classes=None, writable=False)¶ Create a one to many relation to a given target
Resource
.Parameters: dest_class (Resource) – The target class for the relationship
Keyword Arguments: - type (RelationType) – The relationship approach to use.
- writable (bool) – Whether the relationship is mutable.
- reverse (to_may or to_one) – An optional reverse relationship.
- reverse_type (RelationType) – The reverse relationship approach.
- resource_classes (Resource) – The kinds of Resources to expect in the relationship
Returns: A builder function which, given a source class creates a one-to-many relationship with the previously supplied target.
A to-many relationship means that the there are many dest_class resources associated with the given source class. The returned method builder will automatically create methods for fetching the associated objects. If the reverse function is supplied the builder will create the correponding reverse relationship methods on the target class.
@to_many(Sensor, writable=True) class Label: pass # find a label, then fetch sensors sensor = label.sensors()
Since the example above also declares that the relationship is writable you can also add, remove and update all target resources from the source object:
# fetch a couple of sensors then add them to the label label.add_sensors([sensor1, sensor2]) # remove a sensor from the label label.remove_sensors([sensor1]) # remove all sensors from the label label.update_sensors([])
-
helium.relations.
to_one
(dest_class, type='direct', resource_classes=None, reverse=None, reverse_type='direct', writable=False)¶ Create a one to one relation to a given target
Resource
.Parameters: dest_class (Resource) – The target class for the relationship
Keyword Arguments: - type (RelationType) – The relationship approach to use.
- reverse (to_may or to_one) – An optional reverse relationship.
- reverse_type (RelationType) – The reverse relationship approach.
- resource_classes (Resource) – The kinds of Resources to expect in the relationship
Returns: A builder function which, given a source class creates a one-to-one relationship with the target
A one to one relationship means that you can get the associated target object from the object on which the
to_one
was declared.@to_one(Organization) def User(Resource): pass
Declares that a User is associated with one Organization. The decorator automatically adds a method to fetch the associated organization:
org = user.organization()
helium.resource module¶
Base Resource behavior.
-
class
helium.resource.
Base
(json)¶ Bases:
object
A base class to deal with json based attributes.
The base class stores a given json object and dynamically promotes requested object attributes from the cached jason data if they exist.
Sub-classes can override methods to promote attribtues on construction or lazily, when they’re requested
-
class
helium.resource.
Resource
(json, session, include=None, included=None)¶ Bases:
helium.resource.Base
The base class for all Helium resources.
The Helium API uses JSONAPI extensively. The
Resource
object provides a number of useful JSONAPI abstractions.A resource will at least have an
id
attribute, which is promoted from the underlying json data on creation.A resource can be requested to include relation resources in its response using the include request parameter. The
include
argument allows relationship lookups to validate whether the relationship was originally requested. You normally don’t need to specify this since the Resource retrieval methods likeall
andfind
take care of this behavior.-
classmethod
all
(session, include=None)¶ Get all resources of the given resource class.
This should be called on sub-classes only.
The include argument allows relationship fetches to be optimized by including the target resources in the request of the containing resource. For example:
.. code-block:: python
org = Organization.singleton(session, include=[Sensor]) org.sensors(use_included=True)Will fetch the sensors for the authorized organization as part of retrieving the organization. The
use_included
forces the use of included resources and avoids making a separate request to get the sensors for the organization.Parameters: session (Session) – The session to look up the resources in Keyword Arguments: incldue – A list of resource classes to include in the request. Returns: - An iterator over all the resources of
- this type
Return type: iterable(Resource)
-
classmethod
create
(session, attributes=None, relationships=None)¶ Create a resource of the resource.
This should only be called from sub-classes
Parameters: - session (Session) – The session to create the resource in.
- attributes (dict) – Any attributes that are valid for the given resource type.
- relationships (dict) – Any relationships that are valid for the given resource type.
Returns: An instance of a resource.
Return type:
-
delete
()¶ Delete the resource.
Returns: True if the delete is successful. Will throw an error if other errors occur
-
classmethod
find
(session, resource_id, include=None)¶ Retrieve a single resource.
This should only be called from sub-classes.
Parameters: - session (Session) – The session to find the resource in
- resource_id – The
id
for the resource to look up
Keyword Arguments: include – Resource classes to include
Returns: - An instance of a resource, or throws a
NotFoundError
if the resource can not be found.
Return type:
-
is_singleton
()¶ Whether this instance is a singleton.
-
classmethod
singleton
(session, include=None)¶ Get the a singleton API resource.
Some Helium API resources are singletons. The authorized user and organization for a given API key are examples of this.
authorized_user = User.singleton(session)
will retrieve the authorized user for the given
Session
Keyword Arguments: include – Resource classes to include
-
update
(attributes=None)¶ Update this resource.
Not all aspects of a resource can be updated. If the server rejects updates an error will be thrown.
Keyword Arguments: attributes (dict) – Attributes that are to be updated Returns: A new instance of this type of resource with the updated attribute. On errors an exception is thrown. Return type: Resource
-
classmethod
where
(session, include=None, metadata=None, filter=None)¶ Get filtered resources of the given resource class.
This should be called on sub-classes only.
The include argument allows relationship fetches to be optimized by including the target resources in the request of the containing resource. For example:
.. code-block:: python
org = Organization.singleton(session, include=[Sensor]) org.sensors(use_included=True)Will fetch the sensors for the authorized organization as part of retrieving the organization. The
use_included
forces the use of included resources and avoids making a separate request to get the sensors for the organization.The metadata argument enables filtering on resources that support metadata filters. For example:
.. code-block:: python
sensors = Sensor.where(session, metadata={ ‘asset_id’: ‘23456’ })Will fetch all sensors that match the given metadata attribute.
The filter argument enables filtering the resulting resources based on a passed in function. For example:
.. code-block::python
sensors = Sensor.where(session, filter=lambda s: s.name.startswith(“a”))Will fetch all sensors and apply the given filter to only return sensors who’s name start with the given string.
Parameters: session (Session) – The session to look up the resources in
Keyword Arguments: - incldue (list) – The resource classes to include in the request.
- metadata (dict or list) – The metadata filter to apply
Returns: - An iterator over all found resources
of this type
Return type: iterable(Resource)
-
classmethod
-
class
helium.resource.
ResourceMeta
(json)¶ Bases:
helium.resource.Base
Meta information for a resource.
Every
Resource
object in the Helium API has an associated meta object that represents system information for the given resource.Most of this information is specific to the given resource, but all meta instances have at least a
created
andupdated
attribute which are timestamps of when the resource was created and last updated, respectively. These timestamps are in ISO8601 format. To convert them to datetime`s use the `from_iso_date utility function.
helium.sensor module¶
The sensor resource.
-
class
helium.sensor.
Sensor
(json, session, include=None, included=None)¶ Bases:
helium.device.Device
-
element
(use_included=False)¶ Fetch the element associated with this
Sensor
.Returns: The Element
of thisSensor
Return type: Element
-
helium.session module¶
The root entry point for a client to the Helium API.
-
class
helium.session.
CB
¶ Bases:
object
Convenience callback functions for sessions.
This class offers up convenience callback builders that make it easy to use the callback session API to behave like a synchronous API.
-
classmethod
boolean
(true_code, false_code=None)¶ Callback to validate a response code.
The returned callback checks whether a given response has a
status_code
that is considered good (true_code
) and raise an appropriate error if not.The optional
false_code
allows for a non-successful status code to return False instead of throwing an error. This is used, for example in relationship mutation to indicate that the relationship was not modified.Parameters: true_code (int) – The http status code to consider as a success Keyword Arguments: false_code (int) – The http status code to consider a failure Returns: - A function that given a response returns
True
if the - response’s status code matches the given code. Raises
a
HeliumError
if the response code does not match.
- A function that given a response returns
-
classmethod
json
(status_code, process)¶ Callback to validate and extract a JSON object.
The returned callback checks a given response for the given status_code using :function:`response_boolean`. On success the response JSON is parsed and returned.
Parameters: status_code (int) – The http status code to consider a success Returns: - A function that given a response returns the JSON object
- in the given response. Raises a
HeliumError
if the response code does not match.
-
classmethod
-
class
helium.session.
Response
¶ Bases:
helium.session.Response
-
json
()¶
-
-
class
helium.session.
Session
(adapter=None, api_token=None, base_url=u'https://api.helium.com/v1')¶ Bases:
object
Manages a session with Helium Service.
A session with the Helium service. A session is mostly a front for an underlying adapter that implements the details of requesting and handling the responses. Using the adapters allows the use of different syncrhonous and asynchronous approaches. The default adapter is a synchronous requests based adapter.
-
api_token
¶ The API token for to use for this session.
-
datapoints
(timeseries)¶
-
delete
(url, callback, json=None)¶ Delete a URL.
Parameters: - url (string) – URL for the request
- callback (func) – The response callback function
Keyword Arguments: json (dict) – JSON body for the request
Returns: - The result of the callback handling the resopnse from the
executed request
-
get
(url, callback, params=None, json=None, headers=None)¶ Get a URL.
Parameters: callback (func) – The response callback function
Keyword Arguments: - params (dict) – Parameters for the request
- json (dict) – JSON body for the request
- headers (dict) – Additional headers for the request
Returns: - The result of the callback handling the resopnse from the
executed request
-
live
(url, resource_class, resource_args, params=None)¶ Get a live endpoint.
Parameters: - url (string) – URL for the request
- resource_class (class) – The class to use for entries coming from the live endpoint.
- resource_args (dict) – Additional arguments to pass to the resource_class constructor
Keyword Arguments: params (dict) – Request parameters for the live url
Returns: - An iterator over the live endpoint. Depending on the
adapter the iterator will allow asynchronous behavior. The default adapter will block while iterating over the response of this method.
-
patch
(url, callback, params=None, json=None, headers=None)¶ Patch a URL.
Parameters: - url (string) – URL for the request
- callback (func) – The response callback function
- headers (dict) – HTTP headers for the request
Keyword Arguments: - params (dict) – Parameters for the request
- json (dict) – JSON body for the request
Returns: - The result of the callback handling the resopnse from the
executed request
-
post
(url, callback, params=None, json=None, headers=None, files=None)¶ Post to a URL.
Parameters: - url (string) – URL for the request
- callback (func) – The response callback function
- headers (dict) – HTTP headers for the request
Keyword Arguments: - params (dict) – Parameters for the request
- json (dict) – JSON body for the request
Returns: - The result of the callback handling the resopnse from the
executed request
-
put
(url, callback, params=None, json=None, headers=None)¶ Put to a URL.
Parameters: - url (string) – URL for the request
- callback (func) – The response callback function
Keyword Arguments: - params (dict) – Parameters for the request
- json (dict) – JSON body for the request
- headers (dict) – HTTP headers for the request
Returns: - The result of the callback handling the resopnse from the
executed request
-
helium.timeseries module¶
Helium Timeseries functionality.
-
helium.timeseries.
AggregateValue
¶ alias of
agg
-
class
helium.timeseries.
DataPoint
(json, session, **kwargs)¶ Bases:
helium.resource.Resource
Data points for timeseries.
-
sensor_id
¶ The id of the sensor of this data point.
Returns: The id of the sensor that generated this datapoint. Will throw an AttributeError if no sensor id was found in the underlyign data.
-
-
class
helium.timeseries.
Timeseries
(session, resource_class, resource_id, datapoint_class=<class 'helium.timeseries.DataPoint'>, datapoint_id=None, page_size=None, direction=u'prev', start=None, end=None, agg_size=None, agg_type=None, port=None)¶ Bases:
_abcoll.Iterable
A timeseries readings container.
Instances of this class represents a single timeseries query. A timeseries will automatically page forward or backward through the pages returned from the Helium API to return data points that fit within the given arguments.
The timeseries instance is an
Iterable
which can be used to lazily iterate over very large timeseries data sets. The returned timeseries object will not actually start making any requests to the Helium API until you start iterating over it.For example, given:
@timeseries() class Sensor(Resource): pass
You can request a timeseries using:
# Fetch a sensor timeseries = sensor.timeseries() # Get the first 10 readings first10 = timeseries.take(10)
Note that each call to
sensor.timeseries()
will return a new timeseries object which you can iterate over.You can filter timeseries data by specifying
port
,start
orend
dates. Note that start and end dates support a relaxed form of ISO8601:timeseries = sensor.timeseries(start='2016-09-01', end='2016-04-07T19:12:06Z')
You can aggregate numeric timeseries data by specifying
agg_type
andagg_size
. For example, to aggregate minimum, maximum and average temperature readings in 6 hour buckets:timeseries = sensor.timeseries(agg_type='min,max,avg', agg_size='6h', port='t')
The resulting data points will have an aggregate value that will contain the requested aggregates as attributes:
first = list(islice(timeseries, 1))[0] print(first.value.min)
-
create
(port, value, timestamp=None)¶ Post a new reading to a timeseries.
A reading is comprised of a port, a value and a timestamp.
A port is like a tag for the given reading and gives an indication of the meaning of the value.
The value of the reading can be any valid json value.
The timestamp is considered the time the reading was taken, as opposed to the created time of the data-point which represents when the data-point was stored in the Helium API. If the timestamp is not given the server will construct a timestemp upon receiving the new reading.
Parameters: - port (string) – The port to use for the new data-point
- value – The value for the new data-point
Keyword Arguments: timestamp (
datetime
) – An optionaldatetime
object
-
live
()¶ Get a live stream of timeseries readings.
This returns an Iterable over a live stream of readings. Note that the result will need to be closed since the system can not tell when you’ll be done with it.
You can either call
close
on the endpoint when you’re or use the context management facilities of the endpoint.# Fetch a sensor timeseries = sensor.timeseries() # ensure live endpoint closed with timeseries.live() as live: # Wait for 10 readings first10 = list(islice(live, 10))
Returns:
-
take
(n)¶ Return the next n datapoints.
Parameters: n (int) – The number of datapoints to retrieve Returns: A list of at most n datapoints.
-
-
helium.timeseries.
timeseries
()¶ Create a timeseries builder.
Returns: A builder function which, given a class creates a timeseries relationship for that class.
helium.user module¶
The user resource.
-
class
helium.user.
User
(json, session, include=None, included=None)¶ Bases:
helium.resource.Resource
An authorized user of the Helium API.
A user represents a single developer using the Helium API. Each user gets their own API key, which gives them access to all the resources in the
Organization
that the user belongs to.
helium.util module¶
Utility functions.
-
helium.util.
build_request_body
(type, id, attributes=None, relationships=None)¶ Build a request body object.
A body JSON object is used for any of the
update
orcreate
methods onResource
subclasses. In normal library use you should not have to use this function directly.Parameters: - type (string) – The resource type for the attribute
- id (uuid) – The id of the object to update. This may be
None
Keyword Arguments: - attributes (dict) – A JSON dictionary of the attributes to set
- relationships (dict) –
Returns: - A valid attribute dictionary. Often used in the
update
or create
Resource`
methods.
-
helium.util.
build_request_include
(include, params)¶ Augment request parameters with includes.
When one or all resources are requested an additional set of resources can be requested as part of the request. This function extends the given parameters for a request with a list of resource types passed in as a list of
Resource
subclasses.Parameters: - include ([Resource class]) – A list of resource classes to include
- params (dict) – The (optional) dictionary of request parameters to extend
Returns: An updated or new dictionary of parameters extended with an include query parameter.
-
helium.util.
build_request_relationship
(type, ids)¶ Build a relationship list.
A relationship list is used to update relationships between two resources. Setting sensors on a label, for example, uses this function to construct the list of sensor ids to pass to the Helium API.
Parameters: - type (string) – The resource type for the ids in the relationship
- ids ([uuid] or uuid) – Just one or a list of resource uuids to use in the relationship
Returns: A ready to use relationship JSON object.
-
helium.util.
from_iso_date
(str)¶ Convert an ISO8601 to a datetime.
Parameters: str (string) – The ISO8601 formatted string to convert Returns: A datetime
object representing the given time
-
helium.util.
to_iso_date
(timestamp)¶ Convert a UTC timestamp to an ISO8601 string.
datetime instances can be constructed in alternate timezones. This function assumes that the given timestamp is in the UTC timezone.
Parameters: timestamp (datetime) – A datetime object in the UTC timezone. Returns: An ISO8601 formatted string representing the timestamp.