IC Improve Code Recipes

Recipe 16.3 · Python

A Typed Session Wrapper

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

The application stores everything in session: the user, the selected customer, the search filters, a half-finished order, sometimes a whole DataSet. Keys are strings scattered across hundreds of pages, a typo creates a new key silently, and every read is a cast that throws when the session has expired.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Untyped session access with magic keys, casts and large object graphs (p358_r16_3_untyped_session_access_before.py)
"""Untyped session access with magic keys, casts and large object graphs

Source: ImproveCode, Chapter 16, Recipe 16.3 "A Typed Session Wrapper"
Section: The way it's often written
Book page: 358  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Session becomes a server-side session mapping (e.g. Flask-Session); casts become
int()/typing.cast. Usage fragment wrapped in a function.
"""

from collections.abc import MutableMapping
from typing import Any, cast


class Order: ...


# Not to copy: magic strings, casts and object graphs.
def page_code(session: MutableMapping[str, Any], ddl_customer: Any, data_set: Any) -> None:
    customer_id = int(session["CustomerID"])  # KeyError / TypeError
    session["CustomerId"] = ddl_customer.selected_value  # other key

    session["SearchResults"] = data_set  # megabytes
    order = cast(Order, session["CurrentOrder"])
    _ = (customer_id, order)

The improved recipe

Registration and pipeline:

Usage snippet:

Requirements: Python 3.12+. Install: pip install pydantic starlette

Python Typed session wrapper with JSON-serialized values and private keys (p358_r16_3_typed_user_session_wrapper.py)
"""Typed session wrapper with JSON-serialized values and private keys

Source: ImproveCode, Chapter 16, Recipe 16.3 "A Typed Session Wrapper"
Section: The improved recipe
Book page: 358-360  -- original C# listing
Converted from C# to Python.
ISession becomes Starlette's request.session dict (SessionMiddleware); System.Text.Json
becomes pydantic TypeAdapter for round-tripping frozen dataclasses; IHttpContextAccessor
becomes the current Request passed in by a FastAPI dependency.
"""

from collections.abc import MutableMapping
from dataclasses import dataclass
from typing import Any, Protocol

from pydantic import TypeAdapter
from starlette.requests import Request


def set_json[T](session: MutableMapping[str, Any], key: str, value: T) -> None:
    session[key] = TypeAdapter(type(value)).dump_json(value).decode("utf-8")


def get_json[T](session: MutableMapping[str, Any], key: str, type_: type[T]) -> T | None:
    raw = session.get(key)
    return TypeAdapter(type_).validate_json(raw) if raw is not None else None


@dataclass(frozen=True)
class OrderDraftLine:
    sku: str
    quantity: int


@dataclass(frozen=True)
class OrderDraft:
    customer_id: int
    lines: tuple[OrderDraftLine, ...]


class IUserSession(Protocol):
    selected_customer_id: int | None
    order_draft: OrderDraft | None

    def clear(self) -> None: ...


class UserSession:
    _CUSTOMER_KEY = "user.selectedCustomerId"
    _DRAFT_KEY = "user.orderDraft"

    def __init__(self, request: Request | None) -> None:
        self._request = request

    @property
    def _session(self) -> MutableMapping[str, Any]:
        if self._request is None:
            raise RuntimeError("Session is only available during a request.")
        return self._request.session

    @property
    def selected_customer_id(self) -> int | None:
        value = self._session.get(self._CUSTOMER_KEY)
        return int(value) if value is not None else None

    @selected_customer_id.setter
    def selected_customer_id(self, value: int | None) -> None:
        if value is not None:
            self._session[self._CUSTOMER_KEY] = int(value)
        else:
            self._session.pop(self._CUSTOMER_KEY, None)

    @property
    def order_draft(self) -> OrderDraft | None:
        return get_json(self._session, self._DRAFT_KEY, OrderDraft)

    @order_draft.setter
    def order_draft(self, value: OrderDraft | None) -> None:
        if value is None:
            self._session.pop(self._DRAFT_KEY, None)
        else:
            set_json(self._session, self._DRAFT_KEY, value)

    def clear(self) -> None:
        self._session.clear()

Requirements: Python 3.12+. Install: pip install fastapi starlette

Python Configure session middleware with secure cookie settings and expose the typed session (p360_r16_3_session_middleware_setup.py)
"""Configure session middleware with secure cookie settings and expose the typed session

Source: ImproveCode, Chapter 16, Recipe 16.3 "A Typed Session Wrapper"
Section: The improved recipe
Book page: 360-361  -- original C# listing
Converted from C# to Python.
AddSession/UseSession become Starlette SessionMiddleware (signed-cookie store, HttpOnly
by default; max_age is an absolute lifetime, not an idle timeout). The explicit
LoadAsync step is not needed because the cookie session is loaded per request.
"""

from typing import Annotated

from fastapi import Depends, FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware

from p358_r16_3_typed_user_session_wrapper import IUserSession, UserSession

COOKIE_NAME = ".App.Session"


def add_user_session(app: FastAPI, secret_key: str) -> FastAPI:
    # Cookie-backed store: fine for small values. Use a Redis/SQL-backed
    # server-side session for larger state or a farm with shared storage.
    app.add_middleware(
        SessionMiddleware,
        secret_key=secret_key,
        session_cookie=COOKIE_NAME,
        max_age=20 * 60,
        https_only=True,
        same_site="lax",
    )
    return app


def get_user_session(request: Request) -> IUserSession:  # AddScoped<IUserSession, UserSession>
    return UserSession(request)


UserSessionDep = Annotated[IUserSession, Depends(get_user_session)]

Requirements: Python 3.12+. Install: pip install fastapi

Python Store the selected customer in the typed session and redirect to invoices (p361_r16_3_select_customer_endpoint.py)
"""Store the selected customer in the typed session and redirect to invoices

Source: ImproveCode, Chapter 16, Recipe 16.3 "A Typed Session Wrapper"
Section: The improved recipe
Book page: 361  -- original C# listing
Converted from C# to Python.
The controller action becomes a FastAPI route; RedirectToAction becomes url_for + 302.
"""

from fastapi import APIRouter, Request, status
from fastapi.responses import RedirectResponse

from p360_r16_3_session_middleware_setup import UserSessionDep

router = APIRouter()


@router.post("/customers/select/{id}")
def select(id: int, request: Request, user_session: UserSessionDep) -> RedirectResponse:
    user_session.selected_customer_id = id
    return RedirectResponse(request.url_for("invoices_index"), status.HTTP_302_FOUND)

How it works

IUserSession is the only place that knows session keys exist. Pages and services ask for SelectedCustomerId and get an int?: null when it was never set or the session expired, never an exception. Keys are private constants, so a typo can't create a second key. Because it's an interface, a unit test can pass a simple in-memory implementation.

ASP.NET Core session stores bytes in an IDistributedCache, keyed by a cookie. SetJson and GetJson serialize small objects with System.Text.Json, which keeps them readable when you inspect the cache and makes the stored shape explicit. Records like OrderDraft serialize cleanly.

UseUserSession adds the session middleware and then loads the session asynchronously when the browser already has a session cookie. Without LoadAsync, the first access to Session loads it synchronously, which blocks a thread on a network call when the cache is Redis or SQL Server.

Variations and pitfalls

  • Session is not locked. Web Forms took an exclusive lock on session for every page that could write to it (the default), so two requests from the same user ran one after the other. ASP.NET Core doesn't. Two tabs can read the same draft, change it and write it back, and the last write wins. Keep values small and independent, and put anything that must be consistent, like an order, in the database.
  • Session is not for identity. The logged-in user belongs in the authentication cookie, not in Session["User"]. If the session expires before the auth cookie, the user should still be signed in.
  • Store IDs and small state, never DataSets or search results. Re-run the query, or cache it with IMemoryCache keyed by user (Chapter 3).
  • In a web farm, use Microsoft.Extensions.Caching.StackExchangeRedis or Microsoft.Extensions.Caching.SqlServer for the cache, and share Data Protection keys across servers, or the session cookie can't be read on the next server.
  • During a migration, an IUserSession implementation can read from the legacy app's session through the System.Web adapters (Recipe 16.6). Switch the registration when the legacy app is gone; callers don't change.