Core API Reference

This page is the direct API reference.

The User, Device, and Stream objects all inherit from ConnectorObject, meaning that all methods and properties in ConnectorObject can be accessed from any other object in the core API.

The ConnectorDB object is the API main entrance point, and it inherits from Device. When logging in to ConnectorDB, you are logging in as a device, and all operations are done in reference to that device:

import connectordb
cdb = connectordb.ConnectorDB("apikey")
#Prints the full username/devicename path of the logged in device
print cdb.path

This is something you must be aware of when logging in as a user. Using a password actually logs you in as the user device, and all operations are done in reference to this device. Therefore, when logging in as a user, you will need to do the following:

import connectordb
cdb = connectordb.ConnectorDB("username","password")
# cdb is now the username/user device
myuser = cdb.user
# myuser is the "username" user, which can list devices
print myuser.devices()

ConnectorObject

class connectordb._connectorobject.ConnectorObject(database_connection, object_path)[source]

Bases: object

Users, devices and streams are all built upon the base ConnectorObject. The methods from ConnectorObject can be accessed from any user, device or stream.

Do not use this object directly. The API is accessed using the ConnectorDB class (below).

data

Returns the raw dict representing metadata

delete()[source]

Deletes the user/device/stream

description

Allows to directly set the object’s description. Use as a property

exists()[source]

returns true if the object exists, and false otherwise. This is useful for creating streams if they exist:

cdb = connectordb.ConnectorDB("myapikey")

mystream = cdb["mystream"]

if not mystream.exists():
    mystream.create({"type":"string"})
icon

Allows to directly get and set the icon. An icon can be URLencoded (data:image/) or use an icon from the material design set (https://material.io/icons/), prepended with “material:”, and with spaces replaced by underscores.

name

Returns the object’s name. Object names are immutable (unless logged in is a database admin)

nickname

Allows to directly set the object’s user-friendly nickname. Usage is as a property:

cdb.nickname = "My Nickname!"

print cdb.nickname
refresh()[source]

Refresh reloads data from the server. It raises an error if it fails to get the object’s metadata

set(property_dict)[source]

Attempts to set the given properties of the object. An example of this is setting the nickname of the object:

cdb.set({"nickname": "My new nickname"})

note that there is a convenience property cdb.nickname that allows you to get/set the nickname directly.

ConnectorDB

class connectordb._connectordb.ConnectorDB(user_or_apikey=None, user_password=None, url='http://localhost:3124')[source]

Bases: connectordb._device.Device

ConnectorDB is the main entry point for any application that uses the python API. The class accepts both a username and password in order to log in as a user, and accepts an apikey when logging in directly from a device:

import connectordb
cdb = connectordb.ConnectorDB("myusername","mypassword")

#prints "myusername/user" - logging in by username/password combo
#logs in as the user device.
print cdb.path
close()[source]

shuts down all active connections to ConnectorDB

count_devices()[source]

Gets the total number of devices registered with the database. Only available to administrator.

count_streams()[source]

Gets the total number of streams registered with the database. Only available to administrator.

count_users()[source]

Gets the total number of users registered with the database. Only available to administrator.

import_users(directory)[source]

Imports version 1 of ConnectorDB export. These exports can be generated by running user.export(dir), possibly on multiple users.

info()[source]

returns a dictionary of information about the database, including the database version, the transforms and the interpolators supported:

>>>cdb = connectordb.ConnectorDB(apikey)
>>>cdb.info()
{
    "version": "0.3.0",
    "transforms": {
        "sum": {"description": "Returns the sum of all the datapoints that go through the transform"}
        ...
    },
    "interpolators": {
        "closest": {"description": "Uses the datapoint closest to the interpolation timestamp"}
        ...
    }
}
ping()[source]

Pings the ConnectorDB server. Useful for checking if the connection is valid

reset_apikey()[source]

invalidates the device’s current api key, and generates a new one. Resets current auth to use the new apikey, since the change would have future queries fail if they use the old api key.

users()[source]

Returns the list of users in the database

User

class connectordb._user.User(database_connection, object_path)[source]

Bases: connectordb._connectorobject.ConnectorObject

create(email, password, role='user', public=True, **kwargs)[source]

Creates the given user - using the passed in email and password.

You can also set other default properties by passing in the relevant information:

usr.create("my@email","mypass",description="I like trains.")

Furthermore, ConnectorDB permits immediate initialization of an entire user tree, so that you can create all relevant devices and streams in one go:

usr.create("my@email","mypass",devices={
    "device1": {
        "nickname": "My train",
        "streams": {
            "stream1": {
                "schema": "{"type":"string"}",
                "datatype": "train.choochoo"
            }
        },
    }
})

The user and meta devices are created by default. If you want to add streams to the user device, use the “streams” option in place of devices in create.

devices()[source]

Returns the list of devices that belong to the user

email

gets the user’s email address

export(directory)[source]

Exports the ConnectorDB user into the given directory. The resulting export can be imported by using the import command(cdb.import(directory)),

Note that Python cannot export passwords, since the REST API does not expose password hashes. Therefore, the imported user will have password same as username.

The user export function is different than device and stream exports because it outputs a format compatible directly with connectorDB’s import functionality:

connectordb import < mydatabase > <directory >

This also means that you can export multiple users into the same directory without issue

import_device(directory)[source]

Imports a device from the given directory. You export the device by using device.export()

There are two special cases: user and meta devices. If the device name is meta, import_device will not do anything. If the device name is “user”, import_device will overwrite the user device even if it exists already.

public

gets whether the user is public (this means different things based on connectordb permissions setup - connectordb.com has this be whether the user is publically visible. Devices are individually public / private.)

role

Gets the role of the user. This is the permissions level that the user has. It might not be accessible depending on the permissions setup of ConnectorDB. Returns None if not accessible

set_password(new_password)[source]

Sets a new password for the user

streams(public=False, downlink=False, visible=True)[source]

Returns the list of streams that belong to the user. The list can optionally be filtered in 3 ways:

  • public: when True, returns only streams belonging to public devices
  • downlink: If True, returns only downlink streams
  • visible: If True (default), returns only streams of visible devices

Device

class connectordb._device.Device(database_connection, object_path)[source]

Bases: connectordb._connectorobject.ConnectorObject

apikey

gets the device’s api key. Returns None if apikey not accessible.

create(public=False, **kwargs)[source]

Creates the device. Attempts to create private devices by default, but if public is set to true, creates public devices.

You can also set other default properties by passing in the relevant information. For example, setting a device with the given nickname and description:

dev.create(nickname="mydevice", description="This is an example")

Furthermore, ConnectorDB supports creation of a device’s streams immediately, which can considerably speed up device setup:

dev.create(streams={
    "stream1": {"schema": '{"type":"number"}'}
})

Note that the schema must be encoded as a string when creating in this format.

enabled

gets whether the device is enabled. This allows a device to notify ConnectorDB when it is active and when it is not running

export(directory)[source]

Exports the device to the given directory. The directory can’t exist. You can later import this device by running import_device on a user.

import_stream(directory)[source]

Imports a stream from the given directory. You export the Stream by using stream.export()

public

gets whether the device is public (this means different things based on connectordb permissions setup - connectordb.com has this be whether the device is publically visible. Devices are individually public/private.)

reset_apikey()[source]

invalidates the device’s current api key, and generates a new one

role

Gets the role of the device. This is the permissions level that the device has. It might not be accessible depending on the permissions setup of ConnectorDB. Returns None if not accessible

streams()[source]

Returns the list of streams that belong to the device

user

user returns the user which owns the given device

Stream

class connectordb._stream.Stream(database_connection, object_path)[source]

Bases: connectordb._connectorobject.ConnectorObject

__call__(t1=None, t2=None, limit=None, i1=None, i2=None, downlink=False, transform=None)[source]

By calling the stream as a function, you can query it by either time range or index, and further you can perform a custom transform on the stream:

#Returns all datapoints with their data < 50 from the past minute
stream(t1=time.time()-60, transform="if $ < 50")

#Performs an aggregation on the stream, returning a single datapoint
#which contains the sum of the datapoints
stream(transform="sum | if last")
__getitem__(getrange)[source]

Allows accessing the stream just as if it were just one big python array. An example:

#Returns the most recent 5 datapoints from the stream
stream[-5:]

#Returns all the data the stream holds.
stream[:]

In order to perform transforms on the stream and to aggreagate data, look at __call__, which allows getting index ranges along with a transform.

__len__()[source]

taking len(stream) returns the number of datapoints saved within the database for the stream

__module__ = 'connectordb._stream'
__repr__()[source]

Returns a string representation of the stream

append(data)[source]

Same as insert, using the pythonic array name

create(schema='{}', **kwargs)[source]

Creates a stream given an optional JSON schema encoded as a python dict. You can also add other properties of the stream, such as the icon, datatype or description. Create accepts both a string schema and a dict-encoded schema.

datatype

returns the stream’s registered datatype. The datatype suggests how the stream can be processed.

device

returns the device which owns the given stream

returns whether the stream is a downlink, meaning that it accepts input (like turning lights on/off)

ephemeral

returns whether the stream is ephemeral, meaning that data is not saved, but just passes through the messaging system.

export(directory)[source]

Exports the stream to the given directory. The directory can’t exist. You can later import this device by running import_stream on a device.

insert(data)[source]

insert inserts one datapoint with the given data, and appends it to the end of the stream:

s = cdb["mystream"]

s.create({"type": "string"})

s.insert("Hello World!")
insert_array(datapoint_array, restamp=False)[source]

given an array of datapoints, inserts them to the stream. This is different from insert(), because it requires an array of valid datapoints, whereas insert only requires the data portion of the datapoint, and fills out the rest:

s = cdb["mystream"]
s.create({"type": "number"})

s.insert_array([{"d": 4, "t": time.time()},{"d": 5, "t": time.time()}], restamp=False)

The optional restamp parameter specifies whether or not the database should rewrite the timestamps of datapoints which have a timestamp that is less than one that already exists in the database.

That is, if restamp is False, and a datapoint has a timestamp less than a datapoint that already exists in the database, then the insert will fail. If restamp is True, then all datapoints with timestamps below the datapoints already in the database will have their timestamps overwritten to the same timestamp as the most recent datapoint hat already exists in the database, and the insert will succeed.

length(downlink=False)[source]
schema

Returns the JSON schema of the stream as a python dict.

sschema

Returns the JSON schema of the stream as a string

subscribe(callback, transform='', downlink=False)[source]

Subscribes to the stream, running the callback function each time datapoints are inserted into the given stream. There is an optional transform to the datapoints, and a downlink parameter.:

s = cdb["mystream"]

def subscription_callback(stream,data):
    print stream, data

s.subscribe(subscription_callback)

The downlink parameter is for downlink streams - it allows to subscribe to the downlink substream, before it is acknowledged. This is especially useful for something like lights - have lights be a boolean downlink stream, and the light itself be subscribed to the downlink, so that other devices can write to the light, turning it on and off:

def light_control(stream,data):
    light_boolean = data[0]["d"]
    print "Setting light to", light_boolean
    set_light(light_boolean)

    #Acknowledge the write
    return True

# We don't care about intermediate values, we only want the most recent setting
# of the light, meaning we want the "if last" transform
s.subscribe(light_control, downlink=True, transform="if last")
unsubscribe(transform='', downlink=False)[source]

Unsubscribes from a previously subscribed stream. Note that the same values of transform and downlink must be passed in order to do the correct unsubscribe:

s.subscribe(callback,transform="if last")
s.unsubscribe(transform="if last")
user

user returns the user which owns the given stream

connectordb._stream.query_maker(t1=None, t2=None, limit=None, i1=None, i2=None, transform=None, downlink=False)[source]

query_maker takes the optional arguments and constructs a json query for a stream’s datapoints using it:

#{"t1": 5, "transform": "if $ > 5"}
print query_maker(t1=5,transform="if $ > 5")