session.Session
session.Session()Interface definition for Session-like classes, like AppSession, SessionProxy, and ExpressStubSession.
Methods
| Name | Description |
|---|---|
| close | Close the session. |
| destroy | Destroy this session or module scope, including all descendant scopes. |
| download | Deprecated. Please use download instead. |
| dynamic_route | Register a function to call when a dynamically generated, session-specific, route is requested. |
| is_stub_session | Returns whether this is a stub session. |
| on_destroy | Register a callback to run when this session or module scope is destroyed. |
| on_ended | Registers a function to be called after the client has disconnected. |
| on_flush | Register a function to call before the next reactive flush. |
| on_flushed | Register a function to call after the next reactive flush. |
| send_custom_message | Send a message to the client. |
| send_input_message | Send an input message to the session. |
| set_message_handler | Set a client message handler. |
close
session.Session.close(code=1001)Close the session.
destroy
session.Session.destroy()Destroy this session or module scope, including all descendant scopes.
Fires all registered destroy callbacks, then removes all namespaced state from the session. This does not alter the UI; use remove_ui to remove UI elements.
The following categories of state are cleaned up:
- Reactive objects — Effects are stopped, calcs and values are invalidated. After destruction,
get()/set()on a destroyed value raisesDestroyedReactiveError;is_set()returnsFalse. - Inputs — Namespaced input keys and their values are removed. A new module with the same namespace gets fresh input values.
- Outputs — Namespaced output entries are removed and their render effects are destroyed.
- Message handlers, dynamic routes, downloads — Namespaced entries are removed from the root session.
For SessionProxy, this must be called explicitly (typically after removing dynamic module UI). For AppSession, this is called automatically at session end, after all on_ended callbacks.
Idempotent: calling destroy() more than once has no effect.
Composability
Every reactive object — values, calcs, and effects — is scoped to the session (or module session) in which it was created. When you call destroy(), only the objects in that scope are torn down; the parent session and sibling modules are unaffected.
This scoping is what makes modules safe to add and remove dynamically. Without it, destroying one module could leak callbacks or invalidate reactive objects that belong to another part of the app.
The key rule: data that must outlive a module should live outside it. If a reactive value is created inside a module, it is destroyed with the module. If it is created in the caller’s scope and passed in, the module can write to it, and the caller can continue reading it after the module is destroyed.
Returning a reactive value from a module works when the module lives for the entire session. However, if you plan to call session.destroy(), the returned value will be destroyed and can no longer be read:
@module.server
def my_module_server(input, output, session):
result = reactive.value(0)
# ... update result ...
return result
returned_value = my_module_server("editor")
await session.destroy()
returned_value() # Raises DestroyedReactiveError!Instead, pass a reactive value into the module. The value lives in the caller’s scope and survives destruction:
@module.server
def my_module_server(input, output, session, result):
# Module writes to the caller-owned value
@reactive.effect
@reactive.event(input.save)
def _():
result.set(input.data())
# Caller creates and owns the value
saved_data = reactive.value(None)
my_module_server("editor", result=saved_data)
# saved_data is still valid after the module is destroyedSee Also
download
session.Session.download(
id=None,
filename=None,
media_type=None,
encoding='utf-8',
)Deprecated. Please use download instead.
Parameters
Returns
: Callable[[DownloadHandler], None]-
The decorated function.
dynamic_route
session.Session.dynamic_route(name, handler)Register a function to call when a dynamically generated, session-specific, route is requested.
Provides a convenient way to serve-up session-dependent values for other clients/applications to consume.
Parameters
name : str-
A name for the route (used to determine part of the URL path).
handler :DynamicRouteHandler-
The function to call when a request is made to the route. This function should take a single argument (a
starlette.requests.Requestobject) and return astarlette.types.ASGIAppobject.
Returns
: str-
The URL path for the route.
is_stub_session
session.Session.is_stub_session()Returns whether this is a stub session.
In the UI-rendering phase of Shiny Express apps, the session context has a stub session. This stub session is not a real session; it is there only so that code which expects a session can run without raising errors.
on_destroy
session.Session.on_destroy(fn)Register a callback to run when this session or module scope is destroyed.
For SessionProxy (module sessions), destroy callbacks fire when session.destroy() is explicitly called. For AppSession (root sessions), destroy callbacks fire automatically at session end, after all on_ended callbacks have run.
Parameters
on_ended
session.Session.on_ended(fn)Registers a function to be called after the client has disconnected.
Parameters
Returns
: Callable[[], None]-
A function that can be used to cancel the registration.
on_flush
session.Session.on_flush(fn, once=True)Register a function to call before the next reactive flush.
Parameters
Returns
: Callable[[], None]-
A function that can be used to cancel the registration.
on_flushed
session.Session.on_flushed(fn, once=True)Register a function to call after the next reactive flush.
Parameters
Returns
: Callable[[], None]-
A function that can be used to cancel the registration.
send_custom_message
session.Session.send_custom_message(type, message)Send a message to the client.
Parameters
Note
Sends messages to the client which can be handled in JavaScript with Shiny.addCustomMessageHandler(type, function(message){...}). Once the message handler is added, it will be invoked each time send_custom_message() is called on the server.
send_input_message
session.Session.send_input_message(id, message)Send an input message to the session.
Sends a message to an input on the session's client web page; if the input is present and bound on the page at the time the message is received, then the input binding object's receiveMessage(el, message) method will be called. This method should generally not be called directly from Shiny apps, but through friendlier wrapper functions like ui.update_text().
Parameters
set_message_handler
session.Session.set_message_handler(name, handler, *, _handler_session=None)Set a client message handler.
Sets a method that can be called by the client via Shiny.shinyapp.makeRequest(). Shiny.shinyapp.makeRequest() makes a request to the server and waits for a response. By using makeRequest() (JS) and set_message_handler() (python), you can have a much richer communication interaction than just using Input values and re-rendering outputs.
For example, @render.data_frame can have many cells edited. While it is possible to set many input values, if makeRequest() did not exist, the data frame would be updated on the first cell update. This would cause the data frame to be re-rendered, cancelling any pending cell updates. makeRequest() allows for individual cell updates to be sent to the server, processed, and handled by the existing data frame output.
When the message handler is executed, it will be executed within an isolated reactive context and the session context that set the message handler.
Parameters
name : str-
The name of the message handler.
handler : Callable[…, Jsonifiable] | Callable[…, Awaitable[Jsonifiable]] | None-
The handler function to be called when the client makes a message for the given name. The handler function should take any number of arguments that are provided by the client and return a JSON-serializable object. If the value is
None, then the handler atnamewill be removed. **_handler_session** : Optional[Session] = None-
For internal use. This is the session which will be used as the session context when calling the handler.
Returns
: str-
The key under which the handler is stored (or removed). This value will be namespaced when used with a session proxy.