pgwidgets.async_

Asynchronous API for pgwidgets.

Application

class pgwidgets.async_.application.Application(ws_port=9500, http_port=9501, host='127.0.0.1', http_server=True, concurrency_handling='per_session', max_sessions=1, logger=None)

Bases: object

Main entry point for an async pgwidgets application.

Creates a WebSocket server for widget commands and optionally an HTTP server to serve the JS/CSS assets. Each browser connection gets its own Session.

Parameters:
  • ws_port (int) – WebSocket server port (default 9500).

  • http_port (int) – HTTP file server port (default 9501). Ignored if http_server=False.

  • host (str) – Bind address (default ‘127.0.0.1’).

  • http_server (bool) – Whether to start the built-in HTTP server (default True). Set to False if you are serving the pgwidgets static files from your own HTTP/HTTPS server (e.g. FastAPI, aiohttp, nginx).

  • concurrency_handling (str) –

    How widget callbacks are dispatched. One of:

    "per_session" (default)

    Each session gets its own asyncio.Lock. Callbacks within a session are serialized, but different sessions’ callbacks can interleave at await points.

    "serialized"

    All callbacks from all sessions are serialized under a single global asyncio.Lock.

    "concurrent"

    Callbacks are dispatched freely via ensure_future with no serialization.

  • max_sessions (int or None) – Maximum number of concurrent sessions (default 1). Set to None for unlimited. When the limit is reached, new connections are held until an existing session disconnects.

  • logger (logging.Logger or None) – Logger for status messages. If None (default), a null logger is used and no output is produced.

on_connect(handler)

Register a callback invoked when a new session is created.

The handler receives one argument: the Session object. Handler can be sync or async. Use it to build the UI:

@app.on_connect
async def setup(session):
    Widgets = session.get_widgets()
    top = await Widgets.TopLevel(title="Hello")
    await top.show()

Can also be used as a decorator.

on_disconnect(handler)

Register a callback invoked when a session disconnects.

The handler receives one argument: the Session object. Handler can be sync or async. Can also be used as a decorator.

property sessions

Dict of active sessions (session_id -> Session).

property static_path

Path to the pgwidgets static files directory.

property remote_html

Path to the remote.html connector page.

set_favicon(path)

Set a custom favicon for the built-in HTTP server.

Call this before start() to override the default pgwidgets icon.

Parameters:

path (str or Path) – Path to an image file (SVG, PNG, ICO, etc.).

create_session(session_id=None)

Create a session without a browser connection.

The session is registered immediately and can have its widget tree built up before any browser connects. When a browser connects and presents the matching session ID and token, the existing session’s UI will be reconstructed in that browser.

Parameters:

session_id (str or int or None) – An explicit session ID. If None, one is auto-allocated.

Returns:

The newly created session.

Return type:

Session

async start()

Start the WebSocket server (and HTTP server if enabled).

Call this after construction and any customisation. Subclasses can override to add extra setup before or after the servers start.

async close()

Close all sessions and shut down the application.

Causes run() to return so the program can exit cleanly.

async run()

Start servers and run forever. Ctrl-C to exit cleanly.

Session

class pgwidgets.async_.application.Session(app, session_id, ws=None)

Bases: object

A session that owns a widget tree and its associated state.

Sessions persist independently of browser connections. A session can exist with no browser connected (e.g. after a disconnect or when created via Application.create_session()). One or more browsers can connect to the same session.

Parameters:
  • app (Application) – The owning Application.

  • session_id (str or int) – Unique session identifier.

  • ws (websockets.WebSocketServerProtocol or None) – Initial WebSocket connection, if any.

property id

Unique session identifier.

property app

The Application this session belongs to.

property token

Security token for reconnection.

property is_connected

True if at least one browser is connected.

property connections

List of active WebSocket connections.

add_connection(ws)

Add a browser connection to this session.

remove_connection(ws)

Remove a browser connection from this session.

get_widgets()

Return a namespace with widget classes bound to this session.

Usage:

W = session.get_widgets() btn = await W.Button(“Click me”)

Each attribute is a thin wrapper that passes this session as the first argument to the widget class constructor. The returned object is awaitable (two-phase async init).

async make_timer(duration=0)

Create a Timer (non-visual) and return its widget wrapper.

walk_widget_tree()

Yield all widgets in creation/tree order (parents before children).

Starts from root widgets (those with no parent) and recurses depth-first through children.

async reconstruct()

Replay the entire widget tree to all connected browsers.

Walks the widget tree in creation order and for each widget: 1. Sends a create message with constructor args 2. Replays state changes (setters) 3. Attaches children to parents 4. Re-registers callbacks

Sends reconstruct-start / reconstruct-end bracket messages so the browser can suppress its own callback dispatch during reconstruction.

This is called when a browser reconnects to an existing session.

async close()

Close all WebSocket connections for this session.

Widget

class pgwidgets.async_.widget.Widget(session, *args, **kwargs)

Bases: object

Base class for all asynchronous widget wrappers.

Subclasses are generated from widget definitions and have proper constructors with named parameters:

btn = await Button(session, "Click me", icon="path/to/icon.png")

The first argument is always the session. Remaining arguments match the widget definition’s args and options.

Because async operations cannot happen in __init__, the constructor returns a coroutine via __await__ that completes the JS-side creation.

Stores local state so the Python side can serve as the source of truth for the UI.

property session

The Session this widget belongs to.

property app

The Application this widget belongs to.

async on(action, handler, *extra_args, **extra_kwargs)

Register a callback. The handler receives (*callback_args, *extra_args, **extra_kwargs) – no widget arg. Handler can be sync or async.

async add_callback(action, handler, *extra_args, **extra_kwargs)

Register a callback. The handler receives (widget, *callback_args, *extra_args, **extra_kwargs). Handler can be sync or async.

async add_cursor(name, url, hotspot_x, hotspot_y, size=None)

Register a named custom cursor. If url is a local file path it is read and converted to a data URI before sending.

async destroy()

Destroy this widget: tear it down on the JS side and drop it from the Python-side registry so it can be garbage-collected.