Module

middleware.sessions

Session middleware — signed cookie sessions.

Session data is serialized as JSON and signed usingitsdangerous. The session object is stored in a ContextVar, accessible via get_session()from any handler or middleware.

itsdangerousis an optional dependency. If not installed, SessionMiddleware.__init__ raises ConfigurationError.

Classes

SessionConfig 8
Session middleware configuration. ``secret_key`` is required — sessions are signed, not encrypted.

Session middleware configuration.

secret_keyis required — sessions are signed, not encrypted.

Attributes

Name Type Description
secret_key str
cookie_name str
max_age int
path str
domain str | None
secure bool
httponly bool
samesite str
SessionMiddleware 4
Signed cookie session middleware. Reads the session cookie, deserializes and verifies the signatur…

Signed cookie session middleware.

Reads the session cookie, deserializes and verifies the signature, makes the session dict available viaget_session(), then serializes any changes back to a Set-Cookie header on the response.

Usage::

from chirp.middleware.sessions import SessionConfig, SessionMiddleware

app.add_middleware(SessionMiddleware(SessionConfig(
    secret_key="my-secret-key",
)))

# In a handler:
from chirp.middleware.sessions import get_session

@app.route("/dashboard")
def dashboard():
    session = get_session()
    session["visits"] = session.get("visits", 0) + 1
    return f"Visits: {session['visits']}"

Methods

Internal Methods 4
__init__ 1
def __init__(self, config: SessionConfig) -> None
Parameters
Name Type Description
config
_load_session 1 dict[str, Any]
Deserialize and verify the session cookie.
def _load_session(self, request: Request) -> dict[str, Any]
Parameters
Name Type Description
request
Returns
dict[str, Any]
_save_session 2 Response
Serialize the session dict and set the cookie on the response.
def _save_session(self, response: Response, session: dict[str, Any]) -> Response
Parameters
Name Type Description
response
session
Returns
Response
__call__ 2 Response
Load session, dispatch, then save session to response.
async
async def __call__(self, request: Request, next: Next) -> Response
Parameters
Name Type Description
request
next
Returns
Response

Functions

get_session 0 dict[str, Any]
Return the current session dict. Raises ``LookupError`` if called outside a re…
def get_session() -> dict[str, Any]

Return the current session dict.

RaisesLookupErrorif called outside a request with SessionMiddlewareactive.

Returns
dict[str, Any]
regenerate_session 0 dict[str, Any]
Clear the session and return a fresh empty dict. Prevents session fixation by …
def regenerate_session() -> dict[str, Any]

Clear the session and return a fresh empty dict.

Prevents session fixation by discarding all data from the previous session. TheSessionMiddlewarere-signs the new (empty) dict on the response, producing a fresh cookie value.

Called automatically bylogin() and logout(). Can also be called directly when you need to rotate the session::

from chirp.middleware.sessions import regenerate_session

regenerate_session()  # old data gone, new cookie on response

RaisesLookupErrorif called outside a request with SessionMiddlewareactive.

Returns
dict[str, Any]