pgwidgets.sync¶
Synchronous API for pgwidgets.
Application¶
- class pgwidgets.sync.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:
objectMain entry point for a synchronous 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. Flask, FastAPI, nginx).
concurrency_handling (str) –
How widget callbacks are dispatched. One of:
"per_session"(default)Each session gets its own thread. Callbacks within a session are dispatched sequentially on that thread, but different sessions run concurrently. No locks needed within a session.
"serialized"All callbacks from all sessions are dispatched on the main thread inside run(). Simple single-threaded model, but one slow callback blocks every session.
"concurrent"Each callback fires on its own daemon thread. Maximum concurrency, but the caller must manage thread safety for any shared state.
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. Use it to build the UI for that session:
def on_connect(session): Widgets = session.get_widgets() top = Widgets.TopLevel(title="Hello") top.show() app.on_connect(on_connect)
Can also be used as a decorator:
@app.on_connect def setup(session): ...
- on_disconnect(handler)¶
Register a callback invoked when a session disconnects.
The handler receives one argument: the Session object. Can also be used as a decorator.
- 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.
- 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.
- property sessions¶
Dict of active sessions (session_id -> Session).
- property url¶
URL to open in a browser to connect (built-in server only).
- property static_path¶
Path to the pgwidgets static files directory. Useful when serving files from your own HTTP server.
- property remote_html¶
Path to the remote.html connector page. Useful when serving from your own HTTP server.
- 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.).
- close()¶
Close all sessions and stop the application.
Destroys every session (closing browser connections and stopping per-session threads), stops the HTTP server (if running), and signals run() to return.
- run()¶
Start servers and block forever processing callbacks. Ctrl-C to exit.
Calls start() automatically if it hasn’t been called yet.
In
serializedmode, callbacks are dispatched on this thread. Inper_sessionandconcurrentmodes, callbacks run on other threads; this method simply sleeps.
Session¶
- class pgwidgets.sync.application.Session(app, session_id, ws=None)¶
Bases:
objectA 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.
ws (websockets.WebSocketServerProtocol or None) – Initial WebSocket connection, if any.
- property id¶
Unique session identifier.
- property token¶
Security token for reconnection.
- property app¶
The Application this session belongs to.
- 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 = W.Button(“Click me”) vbox = W.VBox(spacing=8)
Each attribute is a thin wrapper that passes this session as the first argument to the widget class constructor.
- gui_do(func, *args, **kwargs)¶
Schedule a function to run on this session’s callback thread. Returns immediately without waiting for the result.
In
serializedmode this queues on the shared main thread. Inper_sessionmode this queues on this session’s thread. Inconcurrentmode this runs directly on the calling thread.
- gui_call(func, *args, **kwargs)¶
Schedule a function to run on this session’s callback thread and block until it completes. Returns the function’s return value.
In
serializedmode this queues on the shared main thread. Inper_sessionmode this queues on this session’s thread. Inconcurrentmode this runs directly on the calling thread.
- 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.
- make_timer(duration=0)¶
Create a Timer (non-visual) and return its widget wrapper.
- 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-endbracket messages so the browser can suppress its own callback dispatch during reconstruction.This is called when a browser reconnects to an existing session.
- close()¶
Close all browser connections for this session.
This triggers the normal disconnect cleanup for each connection. The session itself remains in the Application and can accept new connections.
- destroy()¶
Destroy this session completely.
Closes all browser connections, stops the per-session thread, and removes the session from the Application.
Widget¶
- class pgwidgets.sync.widget.Widget(session, *args, **kwargs)¶
Bases:
objectBase class for all synchronous widget wrappers.
Subclasses are generated from widget definitions and have proper constructors with named parameters:
btn = Button(session, "Click me", icon="path/to/icon.png")
The first argument is always the session. Remaining arguments match the widget definition’s
argsandoptions.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.
- on(action, handler, *extra_args, **extra_kwargs)¶
Register a callback. The handler receives
(*callback_args, *extra_args, **extra_kwargs)– no widget arg.
- add_callback(action, handler, *extra_args, **extra_kwargs)¶
Register a callback. The handler receives
(widget, *callback_args, *extra_args, **extra_kwargs).
- 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.
- 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.