Skip to content

Application state

rn_forge.fastapi.state

Typed application state: declared once, injected through Depends.

app_state(cls) cached

Return the dependency that provides the cls state to a route.

The same dependency object is returned for the same class, so app.dependency_overrides[app_state(cls)] replaces it.

Parameters:

Name Type Description Default
cls type[T]

The state class registered with :func:state_lifespan.

required

Returns:

Type Description
Callable[[Request], T]

A dependency that returns the registered instance of cls; it raises

Callable[[Request], T]

RuntimeError when the application has none.

state_lifespan(cls, opener, inner=None)

Return a lifespan that registers the state opener builds.

Startup enters opener, registers its value under cls, then enters inner. Shutdown exits inner, removes the registration, then exits opener. Nest calls through inner to register several state classes.

Parameters:

Name Type Description Default
cls type[T]

The state class; routes receive it through :func:app_state.

required
opener Callable[[FastAPI], AbstractAsyncContextManager[T]]

Builds the state and releases it on shutdown.

required
inner Lifespan[FastAPI] | None

A lifespan to run while the state is registered.

None

Returns:

Type Description
Lifespan[FastAPI]

A lifespan to pass as lifespan= to the application.

Raises:

Type Description
TypeError

At startup, when the opener yields something that is not an instance of cls; nothing is registered.