Context (c) is the per-request bundle your handler receives, and c.req is the inbound Request. Registration, middleware, and c.match are on Routing; outbound bytes are on Responses.
Import Request from stario.http:
from stario.http import RequestContext#
Context is the per-request bundle the framework constructs before your handler runs. You do not instantiate it yourself.
| Attribute / method | Purpose |
|---|---|
app | The App instance handling this request (create_task, shutdown signaling). |
req | Request: method, path, headers, lazy query/cookies, body readers. |
span | Request telemetry span (covers routing, middleware, and your handler). Use c.span.attr, event, fail for dimensions and errors. |
state | Mutable dict[str, Any]. Middleware stashes values; inner layers and the handler read them. |
match | Immutable Match: .pattern is METHOD plus the URL template; .params are captured {name} / {name...} values. Match.empty on 404 and 405. See Route parameters. |
disconnect | asyncio.Future that completes when the client closes this connection. |
disconnected | True when disconnect has completed. |
shutting_down | True when the server has begun draining this app (same moment as app.shutting_down). |
closing | True when disconnected or shutting_down — handler work should stop. |
alive() | Connection lifecycle helper; see below. |
Send the response with w (Writer); read the inbound message from c.req.
alive()#
Long handlers (SSE, slow streams, relay subscribers) should listen for client disconnect and process shutdown. c.closing supports explicit checkpoint loops. async with c.alive(): installs a watcher that cancels the current task when disconnect or app.shutdown completes first (whichever happens first). async for item in c.alive(source): forwards items from an async iterable until the same cancellation path fires.
Exiting alive() suppresses CancelledError only when cancellation came from this watcher, not from unrelated cancellation elsewhere. Do not use async for c.alive() without a source — use the context manager form.
For response I/O during drain, Writer may still write until disconnected is true even when closing is already true.
See Responses for writer phases and Runtime for shutdown timing.
import asyncio from stario import Context, Writer async def long_poll(c: Context, w: Writer) -> None: async with c.alive(): while True: await asyncio.sleep(0.5) # Task is cancelled when the client drops or the server shuts down.class Context(*args, **kwargs)#
Per-request bundle passed to every handler and middleware.
Context.alive(source=None)#
Watch client disconnect and app shutdown; cancel this task when either happens.
Use async with c.alive(): ... for scoped work, or async for item in c.alive(source): ... to stream from source until disconnect or shutdown. Do not use async for without source; the context-manager form is the supported no-source pattern.
The async for form swallows the disconnect/shutdown cancel only while it waits on source. If the loop body itself awaits, that cancel lands inside the body and propagates. To have it swallowed anywhere in the block, wrap the iteration instead:
async with c.alive(): async for item in source: await send(item)class Route(*parts, method=None, host=None, path=None)#
One HTTP method on one path template.
HOME = Route("GET /")SEND = Route("POST", ROOM + "/send") app.add(SEND, send)at.post(SEND.href(room.id))Route.empty(cls)#
Unmatched 404 / 405 sentinel. Do not register it.
Route.href(*args, query=None, fragment=None, **params)#
Browser URL string. Placeholders are strings; all must be provided.
Request#
Stable view of the request line and headers. The protocol builds it; handlers only read. Reach everything through c.req.
Request fields and accessors#
| Member | How you access it | Notes |
|---|---|---|
| HTTP method | c.req.method | str (e.g. "GET"). Fixed when the request starts. |
| Path | c.req.path | Path only; no query string. Fully percent-decoded. Fixed at start. |
| Raw path | c.req.raw_path | Exact percent-encoded path without the query; routing uses this form. |
| Headers | c.req.headers | RequestHeaders — read-only, case-insensitive; get, getlist, items, etc. |
| Protocol | c.req.protocol_version | str, e.g. "1.1". |
| Keep-alive | c.req.keep_alive | bool. |
| Host | c.req.host | Host header without port, lowercased; IPv6 keeps [...]. Lazy on first read. "" if missing. |
| Query string | c.req.query | ParsedQuery. Lazy. Parsed from the URL ?… portion. |
| Raw query bytes | c.req.query_bytes | Bytes after ? (empty if none). Use when you parse or validate the query yourself. |
| Cookies | c.req.cookies | Read-only Mapping[str, str] merged from Cookie headers. Lazy; do not mutate in place. |
| Body (buffered) | await c.req.body(max_size=None) | Full body as bytes. max_size is the limit for this read; None uses the default from Configuration. |
| Body (stream) | async for chunk in c.req.stream(max_size=None): | Chunked iterator. max_size limits the total bytes, as for body(). Same 413/408/ClientDisconnected. |
Body rules#
RequestPolicy.max_body_bytes (STARIO_REQUESTS_MAX_BODY_BYTES, default 10 MiB) is the default limit for one read. It is not a cap for the server. A handler passes max_size= to body() or stream() to accept more or less. An upload route reads await c.req.body(max_size=6_000_000), and every other route keeps the default.
On body() and stream():
RequestBodyError(413)if the declaredContent-Lengthis above the limit. The read checks the declared length first, so it allocates nothing and sends no100 Continue.RequestBodyError(413)if the body grows past the limit while it is read (a chunked body).RequestBodyError(408)if idle between chunks exceeds the body read timeout (default 30 seconds). BothRequestBodyErrorstatuses answer themselves with the status and a plain body when nothing was sent.RequestBodyErroralso carries400for a body that does not parse and415for an unsupportedContent-Type;read_signalsandread_formraise them.ClientDisconnectedif the peer closes before the body completes. The connection is aborted without a response body.
The server answers 413 before the handler runs only for a Content-Length above 2^31-1 bytes. Every other limit is the handler’s read.
Pick one of body() or stream() per request — switching in either direction raises StarioRuntime. You may call body() multiple times after the first read returns the same bytes. A second stream() on the same request also raises StarioRuntime.
Requests with no body (typical GET): body() returns b""; stream() yields no chunks.
A body that the handler does not read drains up to the default limit. A small declared body (256 KiB or less) drains and keeps the connection. After a larger one, the HTTP/1 connection closes. The close is a lingering close (RFC 9112 9.6): the server sends FIN after the response, then reads and drops input for up to 2 seconds. Thus a browser in the middle of an upload still sees the 413.
Forms and JSON bodies#
The body is bytes. A posted HTML form is application/x-www-form-urlencoded or multipart/form-data; read either with read_form (Forms):
from stario.forms import read_form form = await read_form(c.req)email = form.get("email", "")A JSON body goes through the same codec w.json uses:
import stario.json as stario_json payload = stario_json.loads(await c.req.body())Validate the result with the library you already use. A Datastar request carries its signals as JSON; read those with read_signals on Datastar.
ParsedQuery#
c.req.query is a ParsedQuery, not a flat dict. Repeated keys are preserved.
query.get("key")— first value or default.query.getlist("key")— every value for the key.query.as_dict()— one string per key; first value wins by default (same asget). Passlast=Trueto keep the last value.query.as_lists()— full multi-value map.
Use as_dict() or as_lists() when validating the whole query (for example with Pydantic).
Cookie response headers use stario.cookies with w (Cookies).
class Request(*args, **kwargs)#
One HTTP request. New object per dispatch; not pooled with the exchange.
Headers, query, and host read the exchange arena while the handler runs. If the Request (or its headers / query / cookies) is still referenced when the exchange is recycled, it takes a private copy, so it stays valid after the handler returns. The body is only readable while the handler runs, unless it was already read.
async Request.body(max_size=None)#
async Request.stream(max_chunk=None, max_size=None)#
class ParsedQuery(*args, **kwargs)#
Query index. First read fills C name/value spans.
Names that need no unquote stay on the original bytes. Names with + / %XX get a private copy so they can decode in place. get memcmps typical ASCII names, then decodes only that value. First name= wins. items / as_dict / as_lists decode everything.
ParsedQuery.as_dict(*, last=False)#
ParsedQuery.as_lists()#
ParsedQuery.get(key, default=None)#
ParsedQuery.getlist(key)#
ParsedQuery.items()#
stario.http.RequestHeaders#
Read-only request headers (c.req.headers).
While the handler runs this reads the exchange arena in place. When the exchange is recycled and this view is still referenced, it copies the arena and header table so it keeps answering for this request.
RequestHeaders.add(name, value)#
RequestHeaders.get(name, default=None)#
Value of name, else default. A name no request can carry is absent.
RequestHeaders.getlist(name)#
RequestHeaders.items()#
RequestHeaders.remove(name)#
RequestHeaders.set(name, value)#
RequestHeaders.unsafe_get(name, default=None)#
RequestHeaders.unsafe_getlist(name)#
RequestHeaders.unsafe_items()#
Forms#
stario.forms reads an HTML form: its text fields and its uploaded files.
from stario.forms import Form, UploadFile, read_formread_form(c.req) returns a Form. The method decides where the data is, as in read_signals:
GETandHEADread the query string.Other methods read the body by its
Content-Type:application/x-www-form-urlencodedormultipart/form-data.
Field access matches c.req.query. form.get("name") returns the first value, and form.getlist("name") returns every value in order. items() and as_dict() work as on ParsedQuery. Thus a form that moves from method="get" to method="post" keeps the same handler code.
A multipart body streams. Each file is an UploadFile with filename, content_type, file, and size. file is a SpooledTemporaryFile: it stays in memory up to spool_size, then moves to disk. await upload.read() returns the content. A read from disk runs in a thread, so the event loop keeps serving. form.file("name") returns the first file of a field, form.filelist("name") returns every file, and form.file_items() returns every (name, UploadFile) pair.
from stario.forms import read_form async def report_pet(c, w): with await read_form(c.req, max_size=6_000_000, max_files=1) as form: name = form.get("name", "") photo = form.file("photo") if photo is None: w.text("Add a photo", 400) return data = await photo.read() ...Use with (or call form.close()) to delete the spooled files at once. Otherwise they go when the Form is garbage-collected.
The limits are keyword arguments:
max_size: the whole body, as inbody(). The default isRequestPolicy.max_body_bytes. Raise it on an upload route.max_fields(1000) andmax_field_size(1 MiB): the count of text fields, and the bytes of one multipart text field.max_files(10) andmax_file_size(no limit belowmax_size): the count of files, and the bytes of one file.spool_size(1 MiB): the bytes of one file that stay in memory.
read_form raises RequestBodyError: 400 for a malformed body, 413 past a limit, and 415 for another Content-Type. Values and filenames are untrusted. Validate them, and never use filename as a path. A file input left empty adds no file.
async read_form(req, *, max_size=None, max_fields=1000, max_field_size=1048576, max_files=10, max_file_size=None, spool_size=1048576, max_part_header_bytes=16384)#
Parse the form a client submitted.
max_size: limit of the whole body, as inRequest.body()(default:RequestPolicy.max_body_bytes). Raise it on an upload route.max_fields/max_field_size: count of text fields in a body, and bytes of one multipart text field. GET reads the query, which the header limit of the server already bounds.max_files/max_file_size: count of files in a body, and bytes of one file (default: no limit belowmax_size). A file input left empty is not a file; it counts towardmax_fieldslike an empty field.spool_size: bytes of one file kept in memory before it moves to disk.
Raise RequestBodyError: 400 for a malformed body, 413 past a limit, 415 for another Content-Type. Values are untrusted: validate them. A file input left empty (no filename, no content) adds no file.
from stario.forms import read_form async def report_pet(c, w): with await read_form(c.req, max_size=6_000_000) as form: name = form.get("name", "") photo = form.file("photo")class Form(fields=(), files=())#
Text fields and uploaded files of one form submission.
Close it (or use with form:) to delete spooled files at once; otherwise they go when the Form is garbage-collected.
Form.as_dict(*, last=False)#
One value per text field: the first, or the last with last=True.
Form.close()#
Close every uploaded file and delete its spool.
Form.file(name)#
First file of the field name, else None.
Form.file_items()#
Every file as (name, UploadFile), in order.
Form.filelist(name)#
Every file of the field name (<input type="file" multiple>).
Form.get(name, default=None)#
First value of the text field name, else default.
Form.getlist(name)#
Every value of the text field name, in order.
Form.items()#
Every text field as (name, value), in order.
class UploadFile(filename, content_type, file, size)#
One file part of a multipart/form-data body.
file is a SpooledTemporaryFile: in memory up to the spool size of read_form, then on disk. filename is the client’s name without a path part; it is untrusted, so never use it as a path as it is.
UploadFile.close()#
async UploadFile.read()#
Return the whole content (from the start of the file).
A file that moved to disk is read in a thread, so the event loop keeps serving other requests.