App API

The Model class

class flexx.app.Model(*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.

Parameters:
  • 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).

Notes

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.

Example

class MyModel(Model):

    @event.connect('foo')
    def handle_changes_to_foo_in_python(self, *events):
        ...

    class Both:

        @event.prop
        def foo(self, v=0):
            return float(v)

    class JS:

        BAR = [1, 2, 3]

        def handle_changes_to_foo_in_js(self, *events):
            ...
dispose()

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

id

The unique id of this Model instance.

init()

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.

Parameters:
  • 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.
session

The session object that connects us to the runtime.

sync_props

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 flexx.app.assets. 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 flexx.app.Asset(name, 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.

name

The (file) name of this asset.

remote

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

source

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.

Parameters:
  • 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.
to_string()

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

class flexx.app._assetstore.AssetStore

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 flexx.app.assets. 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.

Parameters:
  • 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.
Returns:

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

Return type:

url

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.

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

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

Return type:

url

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__, ...).

Parameters:
  • 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.
Returns:

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

Return type:

url

export(dirname, clear=False)

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

Parameters:
  • 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_asset(name)

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

get_asset_names()

Get a list of all asset names.

get_associated_assets(mod_name)

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

get_data(name)

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

get_data_names()

Get a list of all data names.

modules

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

update_modules()

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 flexx.app.Session(app_name, store=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.

Responsibilities:

  • 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.

Parameters:
  • 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.
Returns:

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

Return type:

url

app

The Model instance that represents the app.

app_name

The name of the application that this session represents.

assets_to_ignore

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.

close()

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

eval(code)

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_data(name)

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_data_names()

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

get_model_instance_by_id(id)

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

id

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.

present_modules

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

remove_data(name)

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.

runtime

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.

status

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

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