API Reference¶
chumicro_requests¶
The error types every call can raise, the case-insensitive header dict, and the wire helpers (encode_request, parse_url, parse_charset, resolve_redirect_url, ResponseParser) for code that frames its own HTTP.
chumicro_requests
¶
Non-blocking HTTP/1.1 client for CircuitPython, MicroPython, and CPython.
CaseInsensitiveDict
¶
HttpError
¶
Bases: Exception
Base class for every chumicro-requests failure.
HttpTimeoutError
¶
Bases: HttpError
Per-request timeout_ms budget elapsed before the response completed.
ParseState
¶
Streaming response parser states.
ResponseParser
¶
Streaming HTTP/1.1 response parser.
body
property
¶
Body bytes received so far (final once :attr:state is DONE).
__init__(*, max_body_bytes=DEFAULT_MAX_BODY_BYTES, max_header_bytes=DEFAULT_MAX_HEADER_BYTES, body_buffer=None, body_buffer_view=None, stream_body=False)
¶
Construct the parser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_body_bytes
|
int
|
Cap on the buffered body size; ignored when stream_body is set. |
DEFAULT_MAX_BODY_BYTES
|
max_header_bytes
|
int
|
Cap on unparsed staged bytes outside the plain-body state, so it bounds the status line, headers, and chunked-framing lines. |
DEFAULT_MAX_HEADER_BYTES
|
body_buffer
|
bytearray | None
|
Optional caller-owned |
None
|
body_buffer_view
|
memoryview | None
|
Pre-cached |
None
|
stream_body
|
bool
|
When |
False
|
body_free()
¶
Writable staging space in the streamed-body window, in bytes.
read_body_into(buffer)
¶
Copy staged body bytes into caller-owned buffer; return the count.
discard_body()
¶
Drop every staged body byte and reset both cursors.
feed(chunk)
¶
Append chunk to the parser's buffer and advance the state.
feed_eof()
¶
Signal that the peer closed the connection.
encode_request(method, host, path, *, headers=None, body=None, user_agent=None)
¶
Encode an HTTP/1.1 request into bytes ready for the wire.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP verb, sent verbatim. |
required |
host
|
str
|
Value for the |
required |
path
|
str
|
Request-target, typically the URL path + query. |
required |
headers
|
CaseInsensitiveDict | dict | list | tuple | None
|
Optional |
None
|
body
|
bytes | None
|
Optional |
None
|
user_agent
|
str | None
|
Override for the default |
None
|
Returns:
| Type | Description |
|---|---|
bytes
|
Encoded request as |
Raises:
| Type | Description |
|---|---|
HttpURLError
|
A method, path, or header holds CR / LF / NUL or non-ASCII. |
parse_charset(content_type)
¶
Extract the charset=... parameter from a Content-Type header.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content_type
|
str | None
|
Raw |
required |
Returns:
| Type | Description |
|---|---|
str
|
The detected charset name, or |
parse_url(url)
¶
Split url into (scheme, host, port, path).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
HTTP or HTTPS URL to split. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, str, int, str]
|
4-tuple |
Raises:
| Type | Description |
|---|---|
HttpURLError
|
Bad scheme, missing host, or non-integer port. |
resolve_redirect_url(current_url, location)
¶
Resolve a Location header value against the current request URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_url
|
str
|
The URL of the request being redirected. |
required |
location
|
str
|
The raw |
required |
Returns:
| Type | Description |
|---|---|
str
|
Absolute URL the redirected request should target. |
Raises:
| Type | Description |
|---|---|
HttpURLError
|
current_url doesn't parse, or location is empty. |
chumicro_requests.client¶
HttpClient itself, the RequestHandle each call returns, the Response it resolves to, and the WhenOversized policy for bodies past max_body_bytes. from chumicro_requests import HttpClient gives you the same class.
chumicro_requests.client
¶
HTTP/1.1 client built on chumicro-sockets + chumicro-timing.
:class:HttpClient is the entry point.
WhenOversized
¶
Policy for response bodies exceeding max_body_bytes.
Response
¶
Result of a completed HTTP request.
Attributes:
| Name | Type | Description |
|---|---|---|
status_code |
Integer HTTP status (e.g. |
|
reason |
Reason phrase from the status line (e.g. |
|
http_version |
Protocol version string (e.g. |
|
headers |
:class: |
|
body |
Raw response body as |
|
url |
The URL that was requested. |
|
oversized_dropped |
|
|
streamed |
|
encoding
property
writable
¶
Charset used to decode :attr:body into :attr:text.
text
property
¶
:attr:body decoded to str using :attr:encoding.
Raises:
| Type | Description |
|---|---|
UnicodeError
|
The body bytes don't match the encoding. |
HttpError
|
The response is :attr: |
json()
¶
Parse :attr:body as JSON and return the decoded object.
Raises:
| Type | Description |
|---|---|
ValueError
|
The body is not valid JSON. |
RequestHandle
¶
HttpClient
¶
Non-blocking HTTP/1.1 client.
busy
property
¶
True while a request is in flight.
io_socket
property
¶
Underlying pollable socket while in flight, else None.
from_config(config, *, radio=None, ssl_context=None, transport_factory=None, **constructor_kwargs)
classmethod
¶
Build an :class:HttpClient from runtime config.
Config keys carry the deployment-varying values; any other
constructor knob (buffer sizes, budgets, ticks) passes
through verbatim as a keyword, and an explicit keyword wins
over its config-derived value.
__init__(*, transport_factory, recv_budget_per_tick=DEFAULT_RECV_BUDGET_PER_TICK, max_body_bytes=DEFAULT_MAX_BODY_BYTES, max_header_bytes=DEFAULT_MAX_HEADER_BYTES, when_oversized=WhenOversized.DROP_WITH_EVENT, default_timeout_ms=DEFAULT_TIMEOUT_MS, default_max_redirects=DEFAULT_MAX_REDIRECTS, stream_buffer_size=DEFAULT_STREAM_BUFFER_SIZE, user_agent=None, ticks=None)
¶
Wire up the client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transport_factory
|
object
|
Callable |
required |
recv_budget_per_tick
|
int
|
Soft cap on bytes drained per :meth: |
DEFAULT_RECV_BUDGET_PER_TICK
|
max_body_bytes
|
int
|
Cap on a buffered body; not applied to |
DEFAULT_MAX_BODY_BYTES
|
max_header_bytes
|
int
|
Cap on the response's unparsed header section. |
DEFAULT_MAX_HEADER_BYTES
|
when_oversized
|
str
|
Policy for over-cap responses (see :class: |
DROP_WITH_EVENT
|
default_timeout_ms
|
int
|
Default per-request timeout in ms. |
DEFAULT_TIMEOUT_MS
|
default_max_redirects
|
int
|
Default cap on 3xx hops; |
DEFAULT_MAX_REDIRECTS
|
stream_buffer_size
|
int
|
Staging capacity in bytes for each |
DEFAULT_STREAM_BUFFER_SIZE
|
user_agent
|
str | None
|
Override for the default |
None
|
ticks
|
object | None
|
Optional |
None
|
io_interest(now_ms)
¶
Runner poll-interest bit for the current phase.
Read while receiving, write while sending, 0 otherwise.
next_deadline(now_ms)
¶
Return the per-request timeout deadline, or None when idle.
request(method, url, *, body=None, json=None, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)
¶
Issue method against url; return a :class:RequestHandle.
Raises:
| Type | Description |
|---|---|
HttpBusyError
|
A request is already in flight. |
HttpURLError
|
url is not an absolute http/https URL. |
ValueError
|
|
TypeError
|
body is not bytes / bytearray / str. |
get(url, *, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)
¶
Issue a GET request; return a :class:RequestHandle.
Raises the same exceptions as :meth:request.
post(url, *, body=None, json=None, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)
¶
Issue a POST request; return a :class:RequestHandle.
Raises the same exceptions as :meth:request.
put(url, *, body=None, json=None, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)
¶
Issue a PUT request; same body / json / stream semantics as
:meth:post. Raises the same exceptions as :meth:request.
patch(url, *, body=None, json=None, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)
¶
Issue a PATCH request; same body / json / stream semantics as
:meth:post. Raises the same exceptions as :meth:request.
delete(url, *, headers=None, timeout_ms=None, max_redirects=None, on_done=None, stream=False)
¶
Issue a DELETE request; v1 sends no body.
Raises the same exceptions as :meth:request.
check(now_ms)
¶
Return True while a request is in flight, so the runner ticks it.
handle(now_ms)
¶
One tick of progress on the in-flight request.
cancel()
¶
Abort the in-flight request; no-op when idle.
chumicro_requests.generators¶
Opt-in submodule for yield from flows driven by Runner.add_generator. fetch runs a whole request top to bottom and returns the Response; get / post / put / patch / delete are the per-verb forms. For a body too big for RAM, stream returns a BodyReader you pull one chunk per yield from. Import it explicitly; a program that never uses a generator never loads it.
chumicro_requests.generators
¶
One-shot HTTP fetch and streamed-body reads as generators.
Public entry points: :func:fetch, :func:get, :func:post,
:func:put, :func:patch, :func:delete, and :func:stream.
BodyReader
¶
fetch(transport_factory, method, url, *, headers=None, body=None, json=None, max_redirects=None, max_body_bytes=DEFAULT_MAX_BODY_BYTES, timeout_ms=DEFAULT_TIMEOUT_MS, user_agent=None, ticks=None)
¶
Issue one HTTP request and return the :class:Response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transport_factory
|
object
|
Callable |
required |
method
|
str
|
HTTP verb, sent verbatim. |
required |
url
|
str
|
Absolute |
required |
headers
|
object | None
|
Optional dict / iterable of |
None
|
body
|
object | None
|
Optional |
None
|
json
|
object | None
|
Optional JSON body; sets |
None
|
max_redirects
|
int | None
|
Hops to follow before returning the 3xx as-is. |
None
|
max_body_bytes
|
int
|
Hard cap on the response body. |
DEFAULT_MAX_BODY_BYTES
|
timeout_ms
|
int
|
Deadline for the whole request, DNS lookup excluded. |
DEFAULT_TIMEOUT_MS
|
user_agent
|
str | None
|
Override the default |
None
|
ticks
|
object | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
object
|
class: |
Raises:
| Type | Description |
|---|---|
HttpTimeoutError
|
The request exceeded timeout_ms (DNS stall excluded). |
HttpOversizedError
|
Body exceeded max_body_bytes. |
HttpProtocolError
|
Response was not valid HTTP/1.1 or peer closed mid-response. |
HttpURLError
|
url or a redirect |
HttpError
|
The transport failed. |
ValueError
|
Both body and json were given. |
stream(transport_factory, method, url, *, headers=None, body=None, json=None, max_redirects=None, timeout_ms=DEFAULT_TIMEOUT_MS, stream_buffer_size=DEFAULT_STREAM_BUFFER_SIZE, user_agent=None, ticks=None)
¶
Issue one request and return a :class:BodyReader for its body.
Raises:
| Type | Description |
|---|---|
HttpTimeoutError
|
timeout_ms elapsed before headers arrived. |
HttpProtocolError
|
The response was not valid HTTP/1.1. |
HttpURLError
|
url or a redirect |
HttpError
|
The transport failed before headers arrived. |
ValueError
|
Both body and json were given. |
get(transport_factory, url, **kwargs)
¶
One-shot GET; call as yield from get(transport_factory, url).
post(transport_factory, url, **kwargs)
¶
One-shot POST; call as yield from post(transport_factory, url, json=...).
put(transport_factory, url, **kwargs)
¶
One-shot PUT; call as yield from put(transport_factory, url, body=...).
patch(transport_factory, url, **kwargs)
¶
One-shot PATCH; call as yield from patch(transport_factory, url, body=...).
delete(transport_factory, url, **kwargs)
¶
One-shot DELETE; call as yield from delete(transport_factory, url).