State Management
A request-scoped server store for transient coordination, JSON-safe values, and request-local listeners. Do not treat it as durable storage or as PulsePoint browser state.
Context Aware
Access state anywhere in your controllers or components without passing
the request object.
Session Persistence
The manager can serialize into a session bucket, but persistence
requires an explicit request.session to
request.state.session bridge in the app middleware.
Dot Notation
Forget brackets. Access your data cleanly with
state.user.email thanks to our AttributeDict wrapper.
main.py initializes
StateManager but does not mirror
request.session into
request.state.session. The installed manager
also clears loaded state on non-wire requests. Treat state as request-local
unless the app explicitly adds and verifies that bridge; do not rely on it
for redirect flash data.
Basic Usage
Import the StateManager to set and get data. The state is
initialized automatically via Middleware for every request.
from casp.state_manager import StateManager
def page():
# 1. Set JSON-safe state for the current request flow
StateManager.set_state("user",
"name": "Alex",
"role": "Admin"
)
# 2. Get State (Returns AttributeDict)
user = StateManager.get_state("user")
print(f"Hello, user.name") # Dot notation works!
return "Dashboard Loaded"
Reactivity & Listeners
You can subscribe to state changes within the server lifecycle. This is useful for logging, analytics, or triggering side effects when specific data changes.
def log_changes(state):
if "error" in state:
print(f"Error detected: state['error']")
# Subscribe returns an unsubscribe function
unsubscribe = StateManager.subscribe(log_changes)
# Trigger the listener
StateManager.set_state("error", "Invalid Credentials")
API Reference
| Method | Description |
|---|---|
| get_state(key?, initial_value?) |
Retrieves the entire state (if no key) or a specific key. Returns
an AttributeDict for objects.
|
| set_state(key, value) | Updates request state, notifies listeners, and attempts to save JSON into the configured session bucket. |
| reset_state(key?) | Clears a specific key or the entire state if no key is provided. |
| subscribe(fn) | Registers a callback function that runs whenever the state changes. |