Recipe 17.4 · Python
One Home for Session State Instead of 223 Copies
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 way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
Almost every CFATS page needs the current user, the current menu and the currently selected facility. Each page gets them the same way: it declares its own properties over Session. I counted 223 code-behind files that declare a CurrentUserInfo property over Session["CurrentUserInfo"]. There are two base page classes in the project, BasePage and PageBase. Only three pages inherit from either of them. The other 291 derive straight from System.Web.UI.Page.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
From CFATS Manager, abridged to two of the 16 properties on the incident input page.
Each page then repeats SetMasterPageVariables(), which copies ten values from these objects to the master page, and its own "if the facility is null" check. Change a session key, or the type stored under one, and you have 223 files to edit. A page that forgets the null check throws NullReferenceException when a session expires.
The unused base classes tell their own story. PageBase was written to solve exactly this, and it has the right properties. It also has two copy-paste bugs where a getter returns the wrong field. Nobody noticed, because almost nothing used it. A base class has to be adopted when it is created. A base class added in year three is adopted by the next page written, and by nothing else.
Requirements: Python 3.12+. Install: pip install flask
"""Per-page session-backed properties copied into every page class
Source: ImproveCode, Chapter 17, Recipe 17.4 "One Home for Session State Instead of 223 Copies"
Section: The way it's often written
Book page: 394-395 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
The Web Forms page becomes a Flask MethodView using a server-side session (e.g.
Flask-Session) holding whole objects; casts become typing.cast.
"""
from typing import Any, cast
from flask import session
from flask.views import MethodView
class UserInfo: ...
class Facility: ...
# From CFATS Manager: CFATS\IncidentInput.aspx.cs
# lines 19-56 (abridged)
class IncidentInput(MethodView):
# region Page Properties 16
@property
def current_user_info(self) -> UserInfo:
return cast(UserInfo, session["CurrentUserInfo"])
@current_user_info.setter
def current_user_info(self, value: UserInfo) -> None:
session["CurrentUserInfo"] = value
@property
def current_facility(self) -> Facility:
return cast(Facility, session["CurrentFacility"])
@current_facility.setter
def current_facility(self, value: Facility) -> None:
session["CurrentFacility"] = value
# ... 14 more, over session and hidden form state
def get(self) -> Any: ...
The improved recipe
For ASP.NET Core (Razor Pages). No packages beyond the shared framework.
A page filter makes "a facility must be selected" a single rule:
Registration, as a usage snippet:
Call app.UseSession() after UseRouting() and before MapRazorPages().
Requirements: Python 3.12+. Install: pip install starlette
"""One current-context service for user/client claims and the selected facility
Source: ImproveCode, Chapter 17, Recipe 17.4 "One Home for Session State Instead of 223 Copies"
Section: The improved recipe
Book page: 395-396 -- original C# listing
Converted from C# to Python.
IHttpContextAccessor becomes the current Starlette Request; claims are read from the
Principal on request.state.user; session values are JSON strings (json + dataclasses).
"""
import json
from dataclasses import asdict, dataclass
from typing import Protocol
from starlette.requests import Request
NAME_IDENTIFIER = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
# Small, serializable facts about the user's current selection.
@dataclass(frozen=True)
class FacilitySelection:
facility_id: int
facility_name: str
status: str
class CurrentContext(Protocol):
@property
def user_id(self) -> int: ...
@property
def client_id(self) -> int: ...
@property
def facility(self) -> FacilitySelection | None: ...
def select_facility(self, facility: FacilitySelection) -> None: ...
class HttpCurrentContext:
_FACILITY_KEY = "cfats.facility"
def __init__(self, request: Request | None) -> None:
self._request = request
@property
def _http(self) -> Request:
if self._request is None:
raise RuntimeError("No HTTP request.")
return self._request
@property
def user_id(self) -> int:
return self._claim_as_int(NAME_IDENTIFIER)
@property
def client_id(self) -> int:
return self._claim_as_int("client_id")
@property
def facility(self) -> FacilitySelection | None:
raw = self._http.session.get(self._FACILITY_KEY)
return None if raw is None else FacilitySelection(**json.loads(raw))
def select_facility(self, facility: FacilitySelection) -> None:
if facility is None:
raise TypeError("facility must not be None")
self._http.session[self._FACILITY_KEY] = json.dumps(asdict(facility))
def _claim_as_int(self, claim_type: str) -> int:
user = getattr(self._http.state, "user", None)
value = user.find_first_value(claim_type) if user is not None else None
try:
return int(value) # type: ignore[arg-type]
except (TypeError, ValueError):
raise RuntimeError(f"Claim '{claim_type}' is missing or invalid.") from None
Requirements: Python 3.12+. Install: pip install fastapi
"""Single guard that redirects to facility selection when none is chosen
Source: ImproveCode, Chapter 17, Recipe 17.4 "One Home for Session State Instead of 223 Copies"
Section: The improved recipe
Book page: 396-397 -- original C# listing
Converted from C# to Python.
The Razor Pages IAsyncPageFilter becomes a FastAPI router dependency; the exemption
attribute becomes an @allow_without_facility decorator read from scope["endpoint"]; the
redirect is raised as an exception and turned into a 302 by an exception handler.
"""
from collections.abc import Callable
from typing import Annotated, Any
from fastapi import Depends, Request, status
from fastapi.responses import RedirectResponse
from p395_r17_4_http_current_context_session import CurrentContext, HttpCurrentContext
def allow_without_facility[F: Callable[..., Any]](endpoint: F) -> F:
endpoint.__allow_without_facility__ = True # type: ignore[attr-defined]
return endpoint
class FacilityRequired(Exception):
"""Raised to short-circuit the request; handled as a redirect."""
def get_current_context(request: Request) -> CurrentContext:
return HttpCurrentContext(request)
# Runs before every page endpoint: the one place that
# decides what happens when no facility has been chosen.
async def require_facility(
request: Request,
current: Annotated[CurrentContext, Depends(get_current_context)],
) -> None:
endpoint = request.scope.get("endpoint")
exempt = getattr(endpoint, "__allow_without_facility__", False)
if not exempt and current.facility is None:
raise FacilityRequired()
async def facility_required_handler(request: Request, exc: Exception) -> RedirectResponse:
return RedirectResponse("/FacilitySelect", status.HTTP_302_FOUND)
Requirements: Python 3.12+. Install: pip install fastapi starlette
"""Register session, current context and the facility guard for all pages
Source: ImproveCode, Chapter 17, Recipe 17.4 "One Home for Session State Instead of 223 Copies"
Section: The improved recipe
Book page: 397 -- original C# listing
Converted from C# to Python.
AddSession/AddRazorPages conventions become Starlette SessionMiddleware plus an APIRouter
whose dependencies apply require_facility to every page route mounted on it.
"""
from fastapi import APIRouter, Depends, FastAPI
from starlette.middleware.sessions import SessionMiddleware
from p396_r17_4_require_facility_filter import (
FacilityRequired,
facility_required_handler,
require_facility,
)
def add_cfats_context(app: FastAPI, secret_key: str) -> APIRouter:
app.add_middleware(
SessionMiddleware,
secret_key=secret_key,
max_age=20 * 60, # cookie is HttpOnly by default
)
app.add_exception_handler(FacilityRequired, facility_required_handler)
# Every page registered on this router runs the facility guard first.
pages = APIRouter(dependencies=[Depends(require_facility)])
return pages
How it works
Identity moves out of session. The user ID and client ID are claims on the authentication cookie, signed and checked on every request. The original kept a whole UserInfo object in session, including login, permissions and contact details. Session keeps only what is truly session-scoped: the facility the user picked. It is stored as a small JSON record, not a serialized object graph, so a deploy that changes the Facility class can't break every live session.
Pages ask for ICurrentContext by injection. They never see a session key, so there is one place to change one. The filter replaces 200 null checks: a page that can be opened without a facility opts out with [AllowWithoutFacility], and every other page is protected by default. "Safe unless you opt out" is the property PageBase never had.
The ten values copied to the master page each time become a view component or a layout that injects ICurrentContext itself.
Variations and pitfalls
- Don't store models in session. The original put
Facility,UserInfo,MenuInfoand even theIncidentbeing edited in session. That is fine with in-process session on one server and breaks on a web farm or after a recycle. Store IDs and reload. - ViewState properties. Many of the 16 properties were over
ViewState. In Razor Pages those become hidden fields or route values. Protect anything security-relevant withIDataProtectoror, better, look it up again on the server. - Multiple tabs. A facility in session is shared by every tab. If users compare facilities side by side, put the facility ID in the route (
/facility/{id}/incidents) and check access in the filter.
On .NET Framework
You can stop the copying today, before any migration. Create one base page, move the properties into it, and change the Inherits of each page as you touch it. Builds against net472:
as instead of a cast means an expired session gives null, not InvalidCastException.
Requirements: Python 3.12+. Install: pip install flask
"""Legacy-stack base page holding the facility selection and guarding every page
Source: ImproveCode, Chapter 17, Recipe 17.4 "One Home for Session State Instead of 223 Copies"
Section: On .NET Framework
Book page: 398-399 -- original C# listing
Converted from C# to Python.
The Web Forms Page base class becomes a Flask MethodView base; [Serializable] becomes a
plain dataclass stored as a dict in the Flask session; Response.Redirect(endResponse)
becomes returning a redirect before the handler runs.
"""
from dataclasses import asdict, dataclass
from typing import Any
from flask import redirect, session
from flask.views import MethodView
@dataclass
class FacilitySelection:
facility_id: int = 0
facility_name: str = ""
class CfatsPage(MethodView):
_FACILITY_KEY = "CurrentFacility"
requires_facility: bool = True
@property
def current_facility(self) -> FacilitySelection | None:
data = session.get(self._FACILITY_KEY)
return FacilitySelection(**data) if isinstance(data, dict) else None
@current_facility.setter
def current_facility(self, value: FacilitySelection | None) -> None:
session[self._FACILITY_KEY] = asdict(value) if value is not None else None
def dispatch_request(self, *args: Any, **kwargs: Any) -> Any:
if self.requires_facility and self.current_facility is None:
# Returning here stops this request, so the page handler
# never runs without a facility.
return redirect("/FacilitySelect")
return super().dispatch_request(*args, **kwargs)