Session Management
Lila signs session cookies with itsdangerous
(a salted URLSafeTimedSerializer). Signing protects integrity: clients cannot
modify the payload without invalidating the signature. Cookies are signed, not encrypted
— never store passwords, tokens or other secrets in a session.
Session.set_async() recursively removes
password-like keys (password, password_hash,
hashed_password, passwd) before signing; User.to_dict()
hides __private_fields__; the Secure flag is enabled automatically
when APP_URL starts with https://; cookies are
HttpOnly + SameSite=Lax by default; and Lila never signs with an empty
or placeholder SECRET_KEY (it generates .lila_secret with 0600
permissions and warns).
Revocation: these are stateless signed cookies, so deleting the browser cookie
logs out that browser but cannot revoke a copied cookie. Rotating SECRET_KEY
invalidates every session; if you need per-user revocation, keep a session version/timestamp in
the user row and check it in your login_required wrapper.
Cookie vs. server-side storage
Sessions are stateless signed cookies by default. When the serialized payload exceeds
3000 bytes (or is naturally large), Lila stores the payload in the cache backend
(Redis when connected, in-memory otherwise) under session:<id>
and writes only sid:<id> (signed) to the cookie, with a TTL.
With the default CACHE_DRIVER=memory, server-side payloads and
sessions live in one process: running 2+ workers means a large session can be lost when another
worker handles the request. Use CACHE_DRIVER=redis for
multi-worker deployments.
Async API (v2)
Inside route handlers use the async methods. The key= argument selects the cookie
name (default "session"; the auth scaffold uses
"auth").
from lila.core.request import Request
from lila.core.responses import JSONResponse
from lila.core.session import Session
from lila.core.templates import render
@router.post("/login")
async def login(request: Request):
response = render(request, "dashboard", csrf=True)
# Only non-sensitive fields. "password"/"token" would be stripped anyway.
await Session.set({"id": 1, "name": "Lila", "email": "lila@example.com"}, response, key="auth")
return response
@router.get("/dashboard")
async def dashboard(request: Request):
user = await Session.get(request, "auth") # dict or None (bad/expired signature -> None)
if not user:
return JSONResponse({"success": False, "message": "Not authenticated"}, status_code=401)
return {"success": True, "user": user}
@router.get("/logout")
async def logout(request: Request):
response = JSONResponse({"success": True})
await Session.delete(request, response, key="auth")
return response
Session.set_async() returns False and logs the error instead of raising
when the response object is missing or the cookie cannot be written. Other options:
max_age=86400 (default), secure, http_only,
same_site="lax", path="/", domain.
The lifetime passed to Session.set() is stored inside the signed cookie, so
Session.get() honours it automatically (a 30-day "remember me" session no longer expires
after one day). Pass max_age to Session.get() only to enforce a shorter
lifetime. Cookies written by Lila 2.0.0 remain readable (1-day lifetime). With the memory cache,
server-side session payloads are evicted last when the LRU is full.
v1 Compatibility Helpers (sync)
Projects migrating from Lila 1.x can keep using the synchronous helpers. They work outside the event loop and delegate to the same signed-cookie logic:
from lila.core.session import Session
from lila.core.responses import JSONResponse
# Sync setter: v1 argument names are still accepted.
@router.get("/set-session")
async def set_session_example(request: Request):
response = JSONResponse({"message": "Session has been set"})
Session.setSession(
new_val={"user_id": 123, "username": "lila_user"},
response=response,
name_cookie="user_session",
max_age=3600,
)
return response
# Sync getter: verifies the signature and expiry, returns None on failure.
@router.get("/get-session")
async def get_session_example(request: Request):
session_data = Session.getSessionValue(request=request, key="user_session")
if not session_data:
return JSONResponse({"message": "No session found or it expired."}, status_code=401)
return {"session_data": session_data}
# Raw, still-signed cookie value (no verification) - v1 helper.
raw = Session.getSession("user_session", request)
# Sync delete
@router.get("/logout")
async def logout(request: Request):
response = JSONResponse({"message": "Logged out"})
Session.deleteSession(response=response, name_cookie="user_session")
return response
Async aliases also exist: setSession_async, getSession_async and
deleteSession_async. There is no public unsign() method — use
Session.get_async() / Session.getSessionValue().
Flash-style messages (small custom helper)
Lila 2.0 has no built-in flash store. A tiny pattern is to write a short-lived list into its own signed cookie and clear it after rendering:
from lila.core.request import Request
from lila.core.responses import RedirectResponse
from lila.core.session import Session
from lila.core.templates import render
FLASH_COOKIE = "flash"
async def queue_message(response, message: str, category: str = "success") -> None:
"""Queue one message in a signed cookie (max 1 day)."""
await Session.set_async(
[{"message": message, "category": category}],
response,
cookie_name=FLASH_COOKIE,
max_age=86400,
)
async def take_messages(request: Request, response) -> list:
"""Read queued messages and delete the cookie."""
messages = await Session.get_async(request, cookie_name=FLASH_COOKIE) or []
if messages:
await Session.delete_async(request, response, cookie_name=FLASH_COOKIE)
return messages
@router.post("/submit")
async def submit_form(request: Request):
response = RedirectResponse(url="/dashboard", status_code=303)
await queue_message(response, "Your application was submitted successfully!")
return response
@router.get("/dashboard")
async def dashboard(request: Request):
response = render(request, "dashboard")
flashes = await take_messages(request, response)
# Pass them to the template: context={"flashes": flashes}
return response
{% for item in flashes %}
<div class="p-4 mb-4 rounded-xl border {% if item.category == 'success' %}bg-green-50 text-green-800 border-green-200{% else %}bg-blue-50 text-blue-800 border-blue-200{% endif %}">
{{ item.message }}
</div>
{% endfor %}