Python API


class databench.Analysis[source]

Databench’s analysis class.

This contains the analysis code. Every browser connection corresponds to an instance of this class.

Initialization: All initializations should be done in on_connected(). Instance variables (which should be avoided in favor of data) should be initialized in the constructor. Some cleanup can be done in on_disconnected().

Arguments/Parameters: Command line arguments are available at cli_args and the parameters of the HTTP GET request at request_args. request_args is a dictionary of all arguments. Each value of the dictionary is a list of given values for this key even if this key only appeared once in the url (see urllib.parse.parse_qs).

Actions: are captured by specifying a class method starting with on_ followed by the action name. To capture the action run that is emitted with the JavaScript code

// on the JavaScript frontend
d.emit('run', {my_param: 'helloworld'});


# in Python
def on_run(self, my_param):

in Python. Lists are treated as positional arguments and objects as keyword arguments to the function call. If the message is neither of type list nor dict (for example a plain string or float), the function will be called with that as its first parameter.

Writing to a datastore: By default, a Datastore scoped to the current analysis instance is created at data. You can write key-value pairs to it with[key] = value

Similarly, there is a class_data Datastore which is scoped to all instances of this analysis by its class name.

Communicating with the frontend: The default is to change state by changing and entry in data or class_data and let that change propagate to the frontend. Directly calling emit() is also possible.

Outgoing messages: changes to the datastore are emitted to the frontend and this path should usually not be modified. However, databench does provide access to emit() method and to methods that modify a value for a key before it is send out with data_<key>(value) methods.


alias of Datastore

data = None

Data specific to this instance of this analysis and therefore connection.

class_data = None

Data that is shared across all instances of this analysis.

cli_args = None

Command line arguments.

request_args = None

Request arguments.


Initialize datastores for this analysis instance.

This creates instances of Datastore at data and class_data with the datastore domains being the current id and the class name of this analysis respectively.

Overwrite this method to use other datastore backends.


Sets what the emit function for this analysis will be.

emit(signal, message=u'__nomessagetoken__')[source]

Emit a signal to the frontend.

  • signal (str) – name of the signal
  • message – message to send

return value from frontend emit function

Return type:



Default handlers for the “connected” action.

Overwrite to add behavior.

New in version 0.7: Previously, most of this functionality was in on_connect().


Default handler for “disconnected” action.

Overwrite to add behavior.


class databench.Meta(name, analysis_class, analysis_path, extra_routes, cli_args=None)[source]

Meta class referencing an analysis.

  • name (str) – Name of this analysis.
  • analysis_class (databench.Analysis) – Object that should be instantiated for every new websocket connection.
  • analysis_path (str) – Path of the analysis class.
  • extra_routes (list) – [(route, handler, data), …]
  • cli_args (list) – Arguments from the command line.
static run_process(*args, **kwargs)[source]

Executes an action in the analysis with the given message.

It also handles the start and stop signals in the case that message is a dict with a key __process_id.

  • action_name (str) – Name of the action to trigger.
  • message – Message.
  • callback – A callback function when done (e.g. stop in tests).
Return type:



class databench.Datastore(domain, release_storage=False)[source]

Key-value data store.

An in-memory and in-process (not persistent) key-value store.

  • domain – A namespace for the key values. This can be an analysis instance id for data local to an analysis instance or the name of an analysis class for data that is shared across instances of the same analysis.
  • release_storage (bool) – Release storage when the last datastore for a domain closes.

Register a change callback.

Parameters:callback – Function that takes in a key and a value.

Trigger all callbacks that were set with on_change().


Similar to dict.update().

Parameters:key_value_pairs (dict) – A dictionary of key value pairs to update.

Initialize datastore.

Only sets values for keys that are not in the datastore already.

Parameters:key_value_pairs (dict) – A set of key value pairs to use to initialize the datastore.

Close and delete instance.


databench.utils.fig_to_src(figure, image_format='png', dpi=80)[source]

Convert a matplotlib figure to an inline HTML image.

  • figure (matplotlib.Figure) – Figure to display.
  • image_format (str) – png (default) or svg
  • dpi (int) – dots-per-inch for raster graphics.
Return type:



Convert a PNG string to a format that can be passed into a src.

Return type:str

Convert an SVG string to a format that can be passed into a src.

Return type:str


class databench.testing.AnalysisTest(analysis, cli_args=None, request_args=None, meta=None)[source]

Unit test wrapper for an analysis.

  • analysis (databench.Analysis) – The analysis to test.
  • cli_args (str) – Command line interface arguments.
  • request_args (str) – Request arguments.
  • meta – An object with a run_process attribute.

Trigger actions using the trigger method. All outgoing messages to the frontend are captured in emitted_messages.

There are two main options for constructing tests: decorating with gen_test and yield ing futures (block until future is done) or to use wait and stop in callbacks. For detailed information on ioloops within the Tornado testing framework, please consult tornado.testing.


from databench.testing import AnalysisTest
from databench.tests.analyses.parameters.analysis import Parameters
import tornado.testing

class Example(tornado.testing.AsyncTestCase):
    def test_gentest(self):
        test = AnalysisTest(Parameters())
        yield test.trigger('test_data', ['light', 'red'])
        self.assertIn(('data', {'light': 'red'}), test.emitted_messages)

    def test_stopwait(self):
        test = AnalysisTest(Parameters())
        test.trigger('test_data', ['light', 'red'], callback=self.stop)
        self.assertIn(('data', {'light': 'red'}), test.emitted_messages)
trigger(action_name, message='__nomessagetoken__', **kwargs)[source]

Trigger an on callback.

  • action_name (str) – Name of the action to trigger.
  • message – Message.
  • callback – A callback function when done (e.g. stop in tests).
Return type: