Guards & Context — Aquilia Documentation
Comprehensive guide and documentation for Guards & Context in the Aquilia framework. View API reference, examples, and implementation patterns.
Sessions / Context Session Context Manage scoped sessions inside code blocks using SessionContext context managers. Scoped Session Access with SessionContext The SessionContext manager provides scoped asynchronous context managers. They accept the request context (ctx) and handle startup resolution and shutdown commit/rollbacks: 1. authenticated(ctx) An asynchronous context manager that requires an active authenticated session. If no session exists, raises SessionRequiredFault. If the session is not authenticated, raises AUTH_REQUIRED. 2. ensure(ctx) An asynchronous context manager that ensures a session exists. If one is missing from the context, raises SessionRequiredFault. 3. transactional(ctx) A transactional session context that takes a snapshot of the session data dictionary on enter. If any exception is raised inside the context block, it automatically rolls back session modifications to prevent partial/invalid states. from aquilia.sessions import SessionContext # 1. .authenticated() — Context block requiring authentication async def protected_operation(ctx): async with SessionContext.authenticated(ctx) as session: user_id = session.principal.id session["last_action"] = "protected_op" # Committed automatically on exiting the context block successfully # 2. .ensure() — Context block ensuring a session exists async def track_visitor(ctx): async with SessionContext.ensure(ctx) as session: session["visits"] = session.get("visits", 0) + 1 # 3. .transactional() — Context block with automatic snapshot-rollback on exceptions async def critical_update(ctx): async with SessionContext.transactional(ctx) as session: session["balance"] -= 100 # If any exception is raised here, session data is restored to its original snapshot state await process_external_billing() )
Go to Homepage