Skip to content

API Reference

chumicro_http_server

chumicro_http_server

Non-blocking HTTP/1.1 server for CircuitPython, MicroPython, and CPython.

The entry point is :class:HttpServer.

CaseInsensitiveDict

Header dict whose lookups fold to lowercase.

get(name, default=None)

Return the value for name or default if missing.

items()

Yield (original_name, value) pairs in insertion order.

add(name, value)

Append value to an existing header, joining with ,.

RequestParser

Streaming HTTP/1.1 request parser.

body property

Body bytes received so far (final once :attr:state is DONE).

__init__(*, max_body_bytes=DEFAULT_MAX_REQUEST_BODY_BYTES, max_request_line_bytes=DEFAULT_MAX_REQUEST_LINE_BYTES, max_headers_bytes=DEFAULT_MAX_HEADERS_BYTES, body_buffer=None, body_buffer_view=None)

Construct a parser for one request; a caller-owned body buffer lets successive parser instances reuse one allocation.

Parameters:

Name Type Description Default
max_body_bytes int

Body-size cap; a bigger body is rejected with 413.

DEFAULT_MAX_REQUEST_BODY_BYTES
max_request_line_bytes int

Request-line cap; a longer line without a CRLF is rejected with 414.

DEFAULT_MAX_REQUEST_LINE_BYTES
max_headers_bytes int

Header-section cap; crossing it is rejected with 431.

DEFAULT_MAX_HEADERS_BYTES
body_buffer bytearray | None

Optional caller-owned bytearray reused per body; None allocates per body.

None
body_buffer_view memoryview | None

Pre-cached memoryview of body_buffer; made for you when omitted.

None

feed(chunk)

Append chunk to the parser's buffer and advance the state.

Raises:

Type Description
ServerProtocolError

The bytes don't conform to HTTP/1.1.

feed_eof()

Signal that the peer closed.

RequestParseState

Streaming request parser states.

ServerError

Bases: Exception

Base class for chumicro-http-server failures.

ServerHeadersTooLargeError

Bases: ServerLimitError

Header section grew past max_headers_bytes (431).

ServerLimitError

Bases: ServerError

A sender-controlled allocation hit a documented cap.

ServerOversizedError

Bases: ServerLimitError

Request Content-Length exceeds max_body_bytes (413).

ServerProtocolError

Bases: ServerError

Inbound bytes don't conform to HTTP/1.1 (the connection is closed without a response).

ServerRequestLineTooLargeError

Bases: ServerLimitError

Request line grew past max_request_line_bytes without a CRLF (414).

parse_charset(content_type)

Extract the charset=... parameter from a Content-Type header.

Parameters:

Name Type Description Default
content_type str | None

Raw Content-Type header value, or None.

required

Returns:

Type Description
str

The detected charset name, or "utf-8" as the default.

parse_query(raw_query)

Parse a foo=bar&baz=qux query string into a header-shaped dict.

split_target(target)

Split a request-target into (path, raw_query).

chumicro_http_server.server

The server module's entry points (HttpServer, Request, Response, build_response, encode_response) resolve lazily through the package, so their reference renders from the module itself.

chumicro_http_server.server

HTTP/1.1 server built on chumicro-sockets and chumicro-timing.

The entry point is :class:HttpServer.

Request

Immutable view of a parsed HTTP request as the handler sees it.

Attributes:

Name Type Description
method

HTTP verb (e.g. "GET").

target

Raw request-target, e.g. "/api/widgets?page=2".

path

Just the path component of the target.

query

:class:CaseInsensitiveDict of query params; percent-encoding is not decoded.

http_version

e.g. "HTTP/1.1".

headers

:class:CaseInsensitiveDict of request headers.

body

Raw request body as bytes.

peer

(host, port) tuple of the connecting client.

text()

Return :attr:body decoded with the request's Content-Type charset.

json()

Parse :attr:body as JSON; raises ValueError on bad data.

Response

Outbound HTTP response built by :func:build_response.

Attributes:

Name Type Description
status_code

Integer HTTP status (e.g. 200).

reason

Reason phrase; falls back to "Unknown" for codes outside the table.

headers

:class:CaseInsensitiveDict to send; the writer adds Content-Length and Connection: close.

body

Bytes to send as the response body (may be b"").

HttpServer

Non-blocking HTTP/1.1 server.

listening property

True once the listener has been opened.

in_flight property

Number of connections currently mid-pipeline.

from_config(config, *, handler=None, radio=None, ssl_context=None, transport_factory=None, **constructor_kwargs) classmethod

Build an :class:HttpServer from runtime config.

Config keys carry the deployment-varying values; any other constructor knob passes through verbatim as a keyword, and an explicit keyword wins over its config-derived value.

Raises:

Type Description
MissingConfigKey

Exactly one of the TLS cert_path / key_path pair is set.

__init__(*, transport_factory, handler=None, max_connections=DEFAULT_MAX_CONNECTIONS, request_timeout_ms=DEFAULT_REQUEST_TIMEOUT_MS, recv_budget_per_tick=DEFAULT_RECV_BUDGET_PER_TICK, send_budget_per_tick=DEFAULT_SEND_BUDGET_PER_TICK, max_request_body_bytes=DEFAULT_MAX_REQUEST_BODY_BYTES, max_request_line_bytes=DEFAULT_MAX_REQUEST_LINE_BYTES, max_headers_bytes=DEFAULT_MAX_HEADERS_BYTES, stream_buffer_size=DEFAULT_STREAM_BUFFER_SIZE, ticks=None)

Wire up the server.

Parameters:

Name Type Description Default
transport_factory object

Callable () -> ListeningSocket; opens the listener on first handle().

required
handler object | None

Optional fallback (Request) -> Response for unmatched paths; None returns 404.

None
max_connections int

Cap on simultaneous in-flight connections.

DEFAULT_MAX_CONNECTIONS
request_timeout_ms int

Per-connection deadline; a stalled connection is dropped and closed.

DEFAULT_REQUEST_TIMEOUT_MS
recv_budget_per_tick int

Per-connection recv cap per :meth:handle call.

DEFAULT_RECV_BUDGET_PER_TICK
send_budget_per_tick int

Per-connection send cap per :meth:handle call.

DEFAULT_SEND_BUDGET_PER_TICK
max_request_body_bytes int

Buffered-body cap; bigger bodies are rejected with 413.

DEFAULT_MAX_REQUEST_BODY_BYTES
max_request_line_bytes int

Request-line cap; a longer line without a CRLF is rejected with 414.

DEFAULT_MAX_REQUEST_LINE_BYTES
max_headers_bytes int

Header-section cap; more is rejected with 431.

DEFAULT_MAX_HEADERS_BYTES
stream_buffer_size int

Staging-window bytes for a StreamingResponse; minted lazily and reused.

DEFAULT_STREAM_BUFFER_SIZE
ticks object | None

Tick source (ticks_ms / ticks_diff / ticks_add); defaults to chumicro_timing.ticks.

None

route(path, *, methods=('GET',))

Decorator that registers a handler for path and methods.

Parameters:

Name Type Description Default
path str

Route path, optionally ending in one <name> segment.

required
methods object

Methods to register (default ("GET",)); an unknown method on a matched path returns 405.

('GET',)

Returns:

Type Description
object

The decorator, which registers and returns the handler unchanged.

close()

Close the listener and every in-flight connection.

check(now_ms)

Always True: the accept loop must run on every tick.

io_interest(now_ms)

Poll-interest bit for Runner.wait.

Read while the listener is open and a connection slot is free, else none.

next_deadline(now_ms)

Earliest tick at which handle() must run.

handle(now_ms)

One tick of progress: lazy-open listener, accept, advance conns.

encode_response(response)

Serialize a :class:Response into wire bytes.

Raises:

Type Description
ServerProtocolError

The reason phrase or a header name or value carries a CR, LF, or NUL.

build_response(status=200, *, body=None, json=None, text=None, html=None, headers=None)

Build a :class:Response with sensible defaults.

chumicro_http_server.streaming

Opt-in submodule for streamed response bodies; import it explicitly. A server that never streams never loads it.

chumicro_http_server.streaming

Streamed response bodies for chumicro-http-server (opt-in submodule).

The entry points are :class:StreamingResponse and :func:build_streaming_response.

StreamingResponse

A response whose body a byte source produces incrementally.

build_streaming_response(status=200, *, source, content_length=None, headers=None)

Build a :class:StreamingResponse served from a byte source.

Parameters:

Name Type Description Default
status int

HTTP status code (default 200).

200
source object

Fill callable source(buffer) -> int; bytes written, 0 if none ready, or SOURCE_EOF.

required
content_length int | None

Total to frame as Content-Length; None (default) frames chunked.

None
headers object | None

Optional extra headers; do not set Content-Length / Transfer-Encoding / Connection.

None

Returns:

Name Type Description
A StreamingResponse

class:StreamingResponse for the handler to return.

encode_streaming_headers(response)

Serialize a :class:StreamingResponse's header block to wire bytes.

Raises:

Type Description
ServerProtocolError

The reason phrase or a header carries a CR, LF, or NUL.

stage_streaming_response(conn, response)

Encode response's headers onto conn and arm the source drain.

drive_stream_body(conn)

Drain conn's byte source to its socket, framed, up to send_budget bytes this tick.