App reference

Wrapping a Component into an Application

class flexx.app.App(cls, *args, **kwargs)

Specification of a Flexx app.

Strictly speaking, this is a container for a PyComponent/JsComponent class plus the args and kwargs that it is to be instantiated with.

Parameters:
  • cls (Component) – the PyComponent or JsComponent class (e.g. Widget) that represents this app.
  • args – positional arguments used to instantiate the class (and received in its init() method).
  • kwargs – keyword arguments used to initialize the component’s properties.
cls

The Component class that is the basis of this app.

dump(fname=None, link=2)

Get a dictionary of web assets that statically represents the app.

The returned dict contains at least one html file. Any session-specific or shared data is also included. If link is 2/3, all shared assets are included too (and the main document links to them). A link value of 0/1 may be prefered for performance or ease of distribution, but with link 2/3 debugging is easier and multiple apps can share common assets.

When a process only dumps/exports an app, no server is started. Tornado is not even imported (we have a test for this). This makes it possible to use Flexx to dump an app and then serve it with any tool one likes.

Parameters:
  • fname (str, optional) – the name of the main html asset. If not given or None, the name of the component class is used. Must end in .html/.htm/.hta.
  • link (int) –

    whether to link (JS and CSS) assets or embed them: A values of 0/1 is recommended for single (and standalone) apps, while multiple apps can share common assets by using 2/3.

    • 0: all assets are embedded into the main html document.
    • 1: normal assets are embedded, remote assets remain remote.
    • 2: all assets are linked (as separate files). Default.
    • 3: normal assets are linked, remote assets remain remote.
Returns:

A collection of assets.

Return type:

dict

export(filename, link=2, overwrite=True)

Export this app to a static website.

Also see dump(). An app that contains no data, can be exported to a single html document by setting link to 0.

Parameters:
  • filename (str) – Path to write the HTML document to. If the filename ends with .hta, a Windows HTML Application is created. If a directory is given, the app is exported to appname.html in that directory.
  • link (int) –

    whether to link (JS and CSS) assets or embed them:

    • 0: all assets are embedded into the main html document.
    • 1: normal assets are embedded, remote assets remain remote.
    • 2: all assets are linked (as separate files). Default.
    • 3: normal assets are linked, remote assets remain remote.
  • overwrite (bool, optional) – if True (default) will overwrite files that already exist. Otherwise existing files are skipped. The latter makes it possible to efficiently export a series of apps to the same directory and have them share common assets.
freeze(dirname, launch='firefox-app', excludes=('numpy', ), includes=())

Create an executable that can be distributed as a standalone desktop application. This process (known as “freezing”) requires PyInstaller.

Note: this method is experimental. See https://flexx.readthedocs.io/en/stable/freeze.html for more information.

Parameters:
  • dirname (str) – Path to generate the executable in. Some temporary files and directories will be created during the freezing process. The actual executable will be placed in “dist/app_name”, where app_name is the (lowercase) name of the application class.
  • launch (str) – The argument to use for the call to flx.launch(). If set to None, flx.serve() will be used instead, and you will be responsible for connecting a browser.
  • excludes (list) – A list of module names to exclude during freezing. By default Numpy is excluded because PyInstaller detects it even though Flexx does not use it. Override this if you do use Numpy.
  • includes (list) – A list of module name to include during freezing.
is_served

Whether this app is already registered by the app manager.

launch(runtime=None, **runtime_kwargs)

Launch this app as a desktop app in the given runtime. See https://webruntime.readthedocs.io for details.

Parameters:
  • runtime (str) – the runtime to launch the application in. Default ‘app or browser’.
  • runtime_kwargs – kwargs to pass to the webruntime.launch function. A few names are passed to runtime kwargs if not already present (‘title’ and ‘icon’).
Returns:

an instance of the given class.

Return type:

Component

name

The name of the app, i.e. the url path that this app is served at.

publish(name, token, url=None)

Publish this app as static HTML on the web.

This is an experimental feature! We will try to keep your app published, but make no guarantees. We reserve the right to remove apps or shut down the web server completely.

Parameters:
  • name (str) – The name by which to publish this app. Must be unique within the scope of the published site.
  • token (str) – a secret token. This is stored at the target website. Subsequent publications of the same app name must have the same token.
  • url (str) – The url to POST the app to. If None (default), the default Flexx live website url will be used.
serve(name=None)

Start serving this app.

This registers the given class with the internal app manager. The app can be loaded via ‘http://hostname:port/name’.

Parameters:name (str, optional) – the relative URL path to serve the app on. If this is '' (the empty string), this will be the main app. If not given or None, the name of the component class is used.
url

The url to acces this app. This raises an error if serve() has not been called yet or if Flexx’ server is not yet running.

flexx.app.serve(cls, name=None, properties=None)

Shorthand for app.App(cls).serve(name).

flexx.app.launch(cls, runtime=None, properties=None, **runtime_kwargs)

Shorthand for app.App(cls).launch(runtime, **runtime_kwargs).

flexx.app.export(cls, filename, properties=None, **kwargs)

Shorthand for app.App(cls).export(filename, ...).

The Component classes

class flexx.app.BaseAppComponent(*init_args, **property_values)

Inherits from Component

Abstract class for Component classes that can be “shared” between Python and JavaScript. The concrete implementations are:

  • The PyComponent class, which operates in Python, but has a proxy object in JavaSript to which properties are synced and from which actions can be invoked.
  • The JsComponent class, which operates in JavaScript, but can have a proxy object in Python to which properties are synced and from which actions can be invoked.
  • The StubComponent class, which represents a component class that is somewhere else, perhaps in another session. It does not have any properties, nor actions. But it can be “moved around”.
root

attribute – The component that represents the root of the application. Alias for session.app.

session

attribute – The session to which this component belongs. The component id is unique within its session.

uid

attribute – A unique identifier for this component; a combination of the session and component id’s.

class flexx.app.PyComponent(*init_args, **property_values)

Inherits from BaseAppComponent

Base component class that operates in Python, but is accessible in JavaScript, where its properties and events can be observed, and actions can be invoked.

PyComponents can only be instantiated in Python, and always have a corresponding proxy object in JS. PyComponents can be disposed only from Python. Disposal also happens if the Python garbage collector collects a PyComponent.

JS

alias of PyComponent

class flexx.app.JsComponent(*init_args, **kwargs)

Inherits from BaseAppComponent

Base component class that operates in JavaScript, but is accessible in Python, where its properties and events can be observed, and actions can be invoked.

JsComponents can be instantiated from both JavaScript and Python. A corresponding proxy component is not necessarily present in Python. It is created automatically when needed (e.g. when referenced by a property). A JsComponent can be explicitly disposed from both Python and JavaScript. When the Python garbage collector collects a JsComponent (or really, the proxy thereof), only the Python side proxy is disposed; the JsComponent in JS itself will be unaffected. Make sure to call dispose() when needed!

JS

alias of JsComponent

class flexx.app.StubComponent(session, id)

Class to represent stub proxy components to take the place of components that do not belong to the current session, or that do not exist for whatever reason. These objects cannot really be used, but they can be moved around.

flexx.app.get_component_classes()

Get a list of all known PyComponent and JsComponent subclasses.

class flexx.app.LocalProperty(*args, doc='', settable=False)

A generic property that is only present at the local side of the component, i.e. not at the proxy. Intended for properties that the other side should not care about, and/or for wich syncing would be problematic, e.g. for performance or because it contains components that we want to keep local.

Session and Assets

An asset is represented using an Asset object that defines its sources, dependencies, etc. Assets can be specific to the session or shared across sessions. 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 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 JsComponent 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:

str

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 use actions to send data to JsComponent 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:

str

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:

str

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 Component 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, request=None)

A connection between Python and the client runtime (JavaScript).

The session 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 process messages received by the client.
  • Keep track of PyComponent instances used by the session.
  • Keep track of JsComponent instances associated with the session.
  • Ensure that the client has all the module definitions it needs.
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. Note that actions can be used to send (binary) data directly to the client (over the websocket).

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:

str

app

The root PyComponent or JsComponent 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.

call_after_roundtrip(callback, *args)

A variant of call_soon() 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()

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

co_eval(js)

Coroutine to evaluate JS in the client, wait for the result, and then return it. It is recomended to use this method only for testing purposes.

co_roundtrip()

Coroutine to wait for one Py-JS-Py roundtrip.

get_component_instance(id)

Get PyComponent or JsComponent instance that is associated with this session and has the corresponding id. The returned value can be None if it does not exist, and a returned component can be disposed.

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.

id

The unique identifier of this session.

keep_alive(ob, iters=1)

Keep an object alive for a certain amount of time, expressed in Python-JS ping roundtrips. This is intended for making JsComponent (i.e. proxy components) survice the time between instantiation triggered from JS and their attachement to a property, 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, consider using actions instead. Note that data is automatically released when the session is closed.

request

The tornado request that was at the origin of this session.

runtime

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

send_command(*command)

Send a command to the other side. Commands consists of at least one argument (a string representing the type of command).

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
  • status 2: connected
  • status 0: closed