Structuring apps

One folder per page. Bootstrap is the only file that knows everything.

A Stario app with one page fits in one file. With two or more, split it by page: one folder per feature, the same files in each, and a bootstrap that wires them together. This page states the rules. Chat room is the example that follows them.

The tree#

app/
  main.py               bootstrap: config, shared objects, register every page
  config.py             frozen Config dataclass, Config.from_env()
  assets.py             ASSETS, STYLE_CSS, DATASTAR_JS
  common/
    shell.py            page(title, body): the <html> document, @baked
  features/
    billing/
      urls.py           Route values and the View of the query; imports only stario
      views.py          render(state, view, ...) and smaller views
      handlers.py       BillingPage: register(app), one method per route
      data.py           schema, reads, and writes, only when the page owns tables
      models.py         dataclasses this feature owns (optional)
  markdown/             code with no URL; it never imports features/
tests/
  conftest.py           client fixture over TestClient(bootstrap)
  test_billing.py

A feature is a page — a resource with its own URL. The path names the resource; the query holds how this tab views it, such as sort or filter. It owns its routes, its HTML, and its page class. It owns tables only if no other feature does; the chat-room lobby has no data.py because it reads the room’s queries.

Code with no URL of its own — an engine, a parser, a client for an outside API, a job runner — lives in app/<name>/, next to features/, and never imports a feature. app/db.py exists only when several features share one connection object.

The tree serves the problem. Split a file when it is hard to read — a feature may add models.py or split views.py — and keep the imports one way.

Name modules after what they hold. db.py and config.py say what is inside; deps.py and utils.py do not.

Routes in urls.py#

Routes are values, so they live in a module that imports only stario. Views import it to build links. Handlers import it to register. Neither imports the other.

# app/features/billing/urls.py
from stario import Route
 
INVOICES_PATH = "/billing/invoices"
INVOICES = Route("GET", INVOICES_PATH)
INVOICE = Route("GET", INVOICES_PATH + "/{invoice_id}")
LIVE = Route("GET", INVOICES_PATH + "/live")
PAY = Route("POST", INVOICES_PATH + "/{invoice_id}/pay")

A page with no action is one GET, plus any private reads — one more GET that reads the signals and patches the part that asked, with no stream and no Relay. Only commands make a page live: the page, a /live stream that pushes HTML, and POST commands that reply and then change state and publish. Live pages explains why.

When the page has a sort or a filter, a View dataclass in urls.py parses the query (View.from_query(c.req.query)) and writes it back (view.query() for links and href(query=...)). The page GET and the stream read the same view, so a reload or a shared link shows the same thing.

Views in views.py#

A view is a function from state to HTML. The main one is render, and it returns the whole document. Smaller views are plain functions it calls. Views import urls.py for href() and nothing from handlers.py.

# app/features/billing/views.py
def render(invoices: list[Invoice], *, user: User) -> HtmlElement:
    return shell(
        h.Main(
            data.init(at.get(LIVE.href(), retry="always")),
            h.H1("Invoices"),
            invoice_table(invoices),
        ),
        user=user,
    )

Handlers in handlers.py#

One shape for every feature: one page class. Its fields are the shared objects the handlers need, register adds every route, and each route is one method that reads top to bottom.

# app/features/billing/handlers.py
@dataclass(frozen=True, slots=True)
class BillingPage:
    db: Database
    relay: Relay[dict]
 
    def register(self, app: App) -> None:
        app.add(INVOICES, self.show)
        app.add(LIVE, self.live)
        app.add(PAY, self.pay)
 
    async def show(self, c: Context, w: Writer) -> None:
        w.html(render(data.list_invoices(self.db), user=current_user(c)))
 
    async def live(self, c: Context, w: Writer) -> None:
        async with self.relay.subscribe("billing.*", latest=True) as events:
            sse = SSE(w)
            sse.patch_elements(render(data.list_invoices(self.db), user=current_user(c)))
            async for _ in c.alive(events):
                sse.patch_elements(render(data.list_invoices(self.db), user=current_user(c)))
 
    async def pay(self, c: Context, w: Writer) -> None:
        invoice_id = c.match.params["invoice_id"]
        w.empty()
        data.mark_paid(self.db, invoice_id)
        self.relay.publish("billing.paid", {})

A static page’s class may hold one config value; a live page’s class holds db and relay. bootstrap builds each page once: BillingPage(db, relay).register(app).

Bootstrap in main.py#

bootstrap is the composition root. It reads config, opens shared objects once, attaches assets, and registers each page. Nothing under app/features/ imports it.

# app/main.py
async def bootstrap(app: App, span: Span):
    config = Config.from_env()
    db = Database(config.db_path)
    db.apply_schema(billing_data.SCHEMA)
    relay: Relay[dict] = Relay()
 
    await ASSETS.attach(app)
    BillingPage(db, relay).register(app)
    yield
    db.close()

Code before yield runs at startup. Code after it runs at shutdown. Runtime has the details.

Middleware#

Register prefix middleware with app.use in bootstrap, in any order, or pass middleware=[...] to app.add for one route.

app.use("/", session.attach)
app.use("/app", session.require)
BillingPage(db, relay).register(app)

A middleware with a dependency is a method of a class built in bootstrap, here session. Register the bound method; no function needs to build the middleware.

Two shipped middleware cover the site-wide baseline: app.use("/", same_origin(), security_headers()) from stario.http rejects cross-origin commands and sets the security headers. same_origin() is the CSRF protection, so forms need no tokens.

Routing states the composition rules.

Tests#

Put tests/ next to app/. The client fixture opens TestClient(bootstrap, request_timeout=5), the same bootstrap production runs, so tests use the real routes and schema. One test per page opens the stream, sends a command, and reads the repaint. Chat room shows that test.

By the way#

  • Keep request parsing that several features share in app/common/. A feature-specific signals.py is fine when only one feature reads that shape.

  • Assets is built at import time in assets.py and attached in bootstrap. Views receive ASSETS.href("css/app.css") as a string. Static assets has the recipe.

  • The complete example is examples/chat-room.