Passing dependencies

Open shared objects once in bootstrap. Hand them to handlers in plain Python.

A handler usually needs a database, an HTTP client, or a Relay. Stario has no injection framework for that. bootstrap opens each shared object once, and the handler receives it the way any Python object receives one: as a field on the page class.

Open long-lived things in bootstrap: a connection pool, an HTTP client, a cache. Short-lived things such as a transaction or a cursor stay inside the handler.

The page class#

A page is one class. Its fields are the dependencies, register adds the routes, and each route is a method.

from dataclasses import dataclass
 
from stario import App, Context, Route, Span, Writer
 
USERS = Route("GET /users")
USER = Route("GET /users/{id}")
 
 
@dataclass(frozen=True, slots=True)
class UsersPage:
    db: Database
 
    def register(self, app: App) -> None:
        app.add(USERS, self.list_users)
        app.add(USER, self.get_user)
 
    async def list_users(self, c: Context, w: Writer) -> None:
        w.json({"users": await self.db.list_users()})
 
    async def get_user(self, c: Context, w: Writer) -> None:
        row = await self.db.fetch_user(c.match.params["id"])
        if row is None:
            w.text("Not found", status=404)
            return
        w.json(row)
 
 
async def bootstrap(app: App, span: Span):
    async with Database.connect() as db:
        UsersPage(db).register(app)
        yield

Both handlers share one db. Nothing is global, and a test can call UsersPage(fake_db).get_user directly. Realtime tiles uses this form.

Several pages share the objects#

Each page class declares the objects it needs as fields, and bootstrap hands the same instances to every page.

async def bootstrap(app: App, span: Span):
    async with Database.connect() as db:
        UsersPage(db).register(app)
        ReportsPage(db).register(app)
        yield

This is the shape in Chat room: LobbyPage(db, relay) and RoomPage(db, relay). Structuring apps puts the class in the feature’s handlers.py.

Several clients#

When bootstrap opens more than one or two context managers, contextlib.AsyncExitStack keeps it flat.

from contextlib import AsyncExitStack
 
 
async def bootstrap(app: App, span: Span):
    async with AsyncExitStack() as stack:
        db = await stack.enter_async_context(Database.connect())
        http = await stack.enter_async_context(httpx.AsyncClient())
        UsersPage(db).register(app)
        ReportsPage(db, http).register(app)
        yield

The stack closes everything in reverse order after the yield.

Dependencies are not request state#

Dependencies live for the whole process. c.state is a dict for one request. Middleware puts the signed-in user or a parsed token in c.state; a handler reads it through a typed function from the same module, such as current_user(c). The database still comes from bootstrap. Runtime describes the lifecycle both sit in.