The Model class

class*init_args, **kwargs)

Subclass of HasEvents representing Python-JavaScript object models.

Each instance of this class has a corresponding object in JavaScript. Events are transparently handled accross the language barrier. To avoid unnecessary communication, only events for which there are handlers at the other side are synchronized.

The JS version of this class is defined by the contained JS class. One can define methods, properties, handlers, and (json serializable) constants on the JS class.

One can also make use of a contained Both class to define things that will be present in both Python and JS. This is intended primarily for defining properties, which can be set on both ends, and which get automatically synchronised.

The init() method on both the Python and JS side can be used to do initialization at a time when properties have their initial values, but handlers are not yet initialized and events are not yet emitted. When a Model instance is assigned as an attribute to the Python instance (inside the init() method), the corresponding attribute will also be present at the JavaScript side.

Initialization order and life cycle:

  • An id and session are associated with the model.
  • The default/initial values for the properties are set.
  • The init() is called. You can get/set properties and attributes here.
  • The handlers are connected. You can use properties here, as well as attributes set in init(). Handlers connected to events that correspond to a property receive an event to communicate the initial value (unless that property does not have a value yet).
  • On the JavaScript side the same order applies. The creation of the JavaScript object occurs after the Python object is created.
  • The JavaScript part of a Model is not garbadge collected, but removed when the Python side object is deleted or disposed using dispose().
  • The Python part of a model is garbadge collected as usual. Note that handlers hold references to the objects that they connect to.
  • Note that the Widget class has a mechanism to avoid being deleted when it is temporarily not referenced due to jitter in the children property.

Models can be used as a context manager to make new Model objects created inside such a context to share the same session. The init() method is invoked in the context of the object itself.

The typical way to use a model is do define properties (preferably in the Both “subclass”) and events, and react to these by writing handlers at the side where the action should be taken. See the example below or many of the examples of the Flexx documentation.

  • session (Session, None) – the session object that connects this instance to a JS client. If not given, will use the session of a currently active model (i.e. as a context manager).
  • is_app (bool) – whether this object is the main app object. Set by Flexx internally. Not used by the Model class, but can be used by subclasses.
  • kwargs – initial property values (see HasEvents).


This class provides the base object for all widget classes in flexx.ui. However, one can also create subclasses that have nothing to do with user interfaces or DOM elements.


class MyModel(Model):

    def handle_changes_to_foo_in_python(self, *events):

    class Both:

        def foo(self, v=0):
            return float(v)

    class JS:

        BAR = [1, 2, 3]

        def handle_changes_to_foo_in_js(self, *events):

Overloaded version of dispose() that removes the global reference of the JS version of the object.


The unique id of this Model instance.


Can be overloaded when creating a custom class to do initialization, such as creating sub models. This function is called with this object as a context manager (the default context is a stub).

send_data(data, meta=None)

Send data to the JS side, where retreive_data() will be called, which will eventually call receive_data() with the corresponding data and meta data.

AJAX is used to retrieve the data. In the future we may want to use a dedicated binary websocket for better performance.

  • data (bytes, str) – the data blob. Can also be a URL (a string starting with “http://”, “https://”, “/flexx/data/” or “_data/”) where the client can download the data from.
  • meta (dict, optional) – information associated with the data that the JS side can use to interpret the data. This function will add an “id” field to the meta data.

The session object that connects us to the runtime.


property – Whether properties are synchronised from JS to Python. This can be set to False if a model has properties that change a lot, but are not of interest for the Python side. Note that events are still synchronised if there is a Python handler.

Session and Assets

An asset is represented using an Asset object that defines its sources, dependencies, etc. Assets can be shared or specific to the session. The AssetStore provides all shared assets for clients connected to the current process. The global store is at The session object handles the connection between Python and the JavaScript, and it allows adding client-side assets, which for instance makes it easy to create extensions based on existing JS libraries.

class, source=None)

Class to represent an asset (JS or CSS) to be included on the page. Users will typically use app.assets.add_shared_asset(), see the corresponding docs for details.


The (file) name of this asset.


Whether the asset is remote (client will load it from elsewhere). If True, the source specifies the URL.


The source for this asset. Can be str, URL or callable.

to_html(path='{}', link=3)

Get HTML element tag to include in the document.

  • path (str) – the path of this asset, in which ‘{}’ can be used as a placeholder for the asset name.
  • link (int) –

    whether to link to this asset:

    • 0: the asset is embedded.
    • 1: normal assets are embedded, remote assets remain remote.
    • 2: the asset is linked (and served by our server).
    • 3: (default) normal assets are linked, remote assets remain remote.

Get the string code for this asset. Even for remote assets.


Provider of shared assets (CSS, JavaScript) and data (images, etc.). Keeps track of JSModules and makes them available via asset bundles. The global asset store object can be found at Assets and data in the asset store can be used by all sessions. Each session object also keeps track of data.

Assets with additional JS or CSS to load can be used simply by creating/importing them in a module that defines the Model class that needs the asset.

add_shared_asset(asset_name, source=None)

Add an asset to the store so that the client can load it from the server. Users typically only need this to provide an asset without loading it in the main page, e.g. when the asset is loaded by a secondary page, a web worker, or AJAX.

  • name (str) – the asset name, e.g. ‘foo.js’ or ‘bar.css’. Can contain slashes to emulate a file system. e.g. ‘spam/foo.js’. If a URL is given, both name and source are implicitly set (and its a remote asset).
  • source (str, function) –

    the source for this asset. Can be:

    • The source code.
    • A URL (str starting with ‘http://‘ or ‘https://‘), making this a “remote asset”. Note that app.export() provides control over how (remote) assets are handled.
    • A funcion that should return the source code, and which is called only when the asset is used. This allows defining assets without causing side effects when they’re not used.

the (relative) url at which the asset can be retrieved.

Return type:


add_shared_data(name, data)

Add data to serve to the client (e.g. images), which is shared between sessions. It is an error to add data with a name that is already registered. See Session.add_data() to set data per-session and Model.send_data()` to send data to Model objects directly.

  • name (str) – the name of the data, e.g. ‘icon.png’.
  • data (bytes) – the data blob.

the (relative) url at which the data can be retrieved.

Return type:


associate_asset(mod_name, asset_name, source=None)

Associate an asset with the given module. The assets will be loaded when the module that it is associated with is used by JavaScript. Multiple assets can be associated with a module, and an asset can be associated with multiple modules.

The intended usage is to write the following inside a module that needs the asset: app.assets.associate_asset(__name__, ...).

  • mod_name (str) – The name of the module to associate the asset with.
  • asset_name (str) – The name of the asset to associate. Can be an already registered asset, or a new asset.
  • source (str, callable, optional) – The source for a new asset. See add_shared_asset() for details. It is an error to supply a source if the asset_name is already registered.

the (relative) url at which the asset can be retrieved.

Return type:


export(dirname, clear=False)

Write all shared data and used assets to the given directory.

  • dirname (str) – the directory to export to. The toplevel directory is created if necessary.
  • clear (bool) – if given and True, the directory is first cleared.

Get the asset instance corresponding to the given name or None if it not known.


Get a list of all asset names.


Get the names of the assets associated with the given module name. Sorted by instantiation time.


Get the data (as bytes) corresponding to the given name or None if it not known.


Get a list of all data names.


The JSModule objects known to the asset store. Each module corresponds to a Python module.


Collect and update the JSModule instances that correspond to Python modules that define Model classes. Any newly created modules get added to all corresponding assets bundles (creating them if needed).

It is safe (and pretty fast) to call this more than once since only missing modules are added. This gets called automatically by the Session object.

class, store=None, request=None)

A session between Python and the client runtime. This class is what holds together the app widget, the web runtime, and the websocket instance that connects to it.


  • Send messages to the client and parse messages received by the client.
  • Keep track of Model instances associated with the session.
  • Ensure that the client has all the module definitions it needs.
  • Allow the user to send data to the client.
add_data(name, data)

Add data to serve to the client (e.g. images), specific to this session. Returns the link at which the data can be retrieved. See Session.send_data() for a send-and-forget mechanism, and app.assets.add_shared_data() to provide shared data.

  • name (str) – the name of the data, e.g. ‘icon.png’. If data has already been set on this name, it is overwritten.
  • data (bytes) – the data blob.

the (relative) url at which the data can be retrieved.

Return type:



The Model instance that represents the app.


The name of the application that this session represents.


The set of names of assets that should not be pushed to the client, e.g. because they are already present on the page. Add names to this set to prevent them from being loaded.

call_after_roundtrip(callback, *args, **kwargs)

A variant of app.call_later() that calls a callback after a py-js roundrip. This can be convenient to delay an action until after other things have settled down.


Close the session: close websocket, close runtime, dispose app.


Evaluate the given JavaScript code in the client

Intended for use during development and debugging. Deployable code should avoid making use of this function.

Gets the value of the cookie with the given name, else default. Note that cookies only really work for web apps.


Get the data corresponding to the given name. This can be data local to the session, or global data. Returns None if data by that name is unknown.


Get a list of names of the data provided by this session.


Get instance of Model class corresponding to the given id, or None if it does not exist.


The unique identifier of this session.

keep_alive(ob, iters=4)

Keep an object alive for a certain amount of time, expressed in Python-JS ping roundtrips. This is intended for making Model objects survive jitter due to synchronisation, though any type of object can be given.


The set of module names that is (currently) available at the client.


Remove the data associated with the given name. If you need this, also consider send_data(). Also note that data is automatically released when the session is closed.


The tornado request that was at the origin of this session


The runtime that is rendering this app instance. Can be None if the client is a browser.

Sets the given cookie name/value with the given options. Set value to None to clear. The cookie value is secured using flexx.config.cookie_secret; don’t forget to set that config value in your server. Additional keyword arguments are set on the Cookie.Morsel directly.


The status of this session. The lifecycle for each session is

  • status 1: pending
  • statys 2: connected
  • status 0: closed