State Management
A powerful, request-scoped store that persists data across redirects. Manage application state with zero boilerplate and full type safety.
Context Aware
Access state anywhere in your controllers or components without passing
the request object.
Session Persistence
Data set in the state automatically survives redirects (Flash Data), perfect for form errors and success messages.
Dot Notation
Forget brackets. Access your data cleanly with
state.user.email thanks to our AttributeDict wrapper.
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 State (Persists to session automatically)
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?, default?) |
Retrieves the entire state (if no key) or a specific key. Returns
an AttributeDict for objects.
|
| set_state(key, value) | Updates the state, notifies listeners, and commits to the session storage. |
| 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. |