Request Context
Async-safe context variables that carry the current user and request through your call stack.
Alata provides request-scoped context variables built on Python's contextvars — values you set once, early in a request, and read anywhere downstream without threading them through every function signature. Because they are ContextVars, they are async-safe: concurrent requests never see each other's values.
The context variables
alata.context defines two variables:
from alata.context import request_context, user_id_context
user_id_context: ContextVar[str | None] # the acting user's id
request_context: ContextVar[dict | None] # arbitrary per-request metadataBoth default to None. Application middleware supplies their values. The scaffold populates user_id_context from identity headers; request_context is available for your own metadata. See middleware for the complete ASGI example.
Setting context from middleware
Set a variable with .set(), which returns a token, and restore the previous value with .reset(token) when the request ends:
from alata.context import request_context
async def handle_with_context(scope, receive, send, app):
token = request_context.set({"tenant": scope.get("state", {}).get("tenant_id")})
try:
await app(scope, receive, send)
finally:
request_context.reset(token)Set user_id_context only when a real identity was resolved — an authenticated user id, or a per-session guest id — never a fallback constant like "anonymous". The rate limiter keys its buckets on this variable, so a constant would merge every unauthenticated caller into one shared bucket; left unset, those callers are keyed per client IP instead.
request_context works the same way — stash whatever per-request dict you find useful (request id, tenant, locale) and read it downstream.
Reading context
Anywhere in the same request's call stack — services, event listeners, query scopes — read the current value with .get():
from alata.context import user_id_context
async def record_audit_entry(action: str) -> None:
await AuditLog.acreate({"action": action, "user_id": user_id_context.get()}).get() returns None when nothing has been set, so code that runs outside a request (CLI commands, workers) keeps working.
Context in exception reports
The exception handler reads user_id_context automatically: its context() method contributes the current user id to every reported exception, so error logs and trackers show who hit the error without any per-callsite effort. Override context() in your application's handler subclass to add more:
from alata.context import request_context
from alata.exceptions.handler import ExceptionHandler
class Handler(ExceptionHandler):
def context(self) -> dict:
ctx = super().context() # includes user_id
ctx.update(request_context.get() or {})
return ctxContext variables live inside one process. They are not serialized with a queued job. External workers run in a different process; the inline sync connection executes in the dispatching process. Pass anything a job needs (like the user id) as an explicit task argument.