Sessions#
Server-side sessions with signed cookie IDs.
Usage#
from asok import Request
def render(request: Request):
# Read
username = request.session.get("username")
# Write
request.session["username"] = "alice"
request.session["cart"] = [1, 2, 3]
return request.html("page.html")
Sessions are lazy-loaded on first access. Modified sessions are automatically saved when the response is sent.
Configuration#
| Key | Default | Description |
|---|---|---|
SESSION_BACKEND | "memory" | "memory" or "file" |
SESSION_PATH | ".sessions" | Directory for file backend |
SESSION_TTL | 86400 | Session lifetime in seconds |
File backend#
app.config["SESSION_BACKEND"] = "file"
app.config["SESSION_PATH"] = ".sessions"
Sessions are stored as JSON files in the specified directory.
How it works#
- A signed cookie (
asok_sid) identifies the session - Session data is stored server-side (memory or file)
- On first
request.sessionaccess, data is loaded from the store - If
session.modifiedisTrueat response time, data is saved back
Session API#
request.session behaves like a regular dict:
request.session["key"] = "value"
request.session.get("key", "default")
del request.session["key"]
request.session.pop("key")
request.session.clear()
All mutating operations automatically set session.modified = True.
Production Persistence#
In production environments using multi-worker servers like Gunicorn, you must use the
filebackend.The default
memorybackend stores sessions in the RAM of the specific worker process. Since requests are distributed across multiple workers, a user will "lose" their session as soon as their request is handled by a different worker.
Configuring for Gunicorn#
To ensure persistence across workers, configure the file backend in your wsgi.py (before application startup):
app.config["SESSION_BACKEND"] = "file"
app.config["SESSION_PATH"] = "/run/asok/sessions" # Using SystemD RuntimeDirectory
For RHEL/AlmaLinux servers, see the Deployment guide for handling SELinux permissions.
Was this page helpful?