httk.serve.http¶
Public lightweight HTTP application helpers.
Submodules¶
Attributes¶
A zero-argument coroutine callback run once, after the response has been sent. |
|
The httk-serve serving application type (a Starlette app; branded so consumers need not import Starlette). |
|
Exceptions¶
Represent an outbound webhook transport or URL-policy failure. |
Classes¶
One valid media range parsed from an HTTP |
|
Send one HTTPS JSON POST through a validated, pinned socket. |
Functions¶
|
Select the best range, discarding any range carrying a parameter. |
|
Select the best range that keeps and matches its parameters. |
|
Decode one token or quoted-string parameter value. |
|
Parse an |
|
Parse a JSON media type into its major, minor, and parameters. |
|
Split an HTTP field outside quoted strings, rejecting broken quoting. |
|
Create an application exposing only explicitly mapped files. |
|
Create a lightweight application serving one live JSON document. |
|
Create a lightweight application serving one live JSON-LD document. |
|
Report whether a value is a valid RFC 9110 field name. |
|
Report whether a value is an acceptable HTTP field value. |
|
Validate response header name-value pairs, rejecting duplicate names. |
|
Report whether a string is free of lone UTF-16 surrogate code points. |
|
Normalise a UUID factory result to the required |
|
Render a timezone-aware datetime as an XSD/RFC 3339 UTC timestamp. |
|
Deliver a document through a sender at most |
|
Append a fixed absolute path without depending on a trailing slash. |
Package Contents¶
- class httk.serve.http.MediaRange[source]¶
One valid media range parsed from an HTTP
Acceptheader.- Parameters:
major – Lowercase major type, or
"*"for a wildcard.minor – Lowercase minor type, or
"*"for a wildcard.parameters – Non-
qparameters as immutable lowercase name-value pairs.quality – The
qweight, defaulting to1.0when absent.
- httk.serve.http.best_quality_ignoring_parameterised(ranges, major, minor)[source]¶
Select the best range, discarding any range carrying a parameter.
Any range that carries a parameter is discarded outright. The specificity tiebreak favours a more specific major/minor match, with a constant second component.
- Parameters:
ranges (tuple[MediaRange, Ellipsis]) – The parsed media ranges to select among.
major (str) – The response major type to match.
minor (str) – The response minor type to match.
- Returns:
The winning range’s quality, or
Nonewhen nothing matches.- Return type:
float | None
- httk.serve.http.best_quality_matching_parameters(ranges, major, minor, parameters)[source]¶
Select the best range that keeps and matches its parameters.
A parameterised range is kept only when every one of its parameters is present and equal in
parameters. The specificity tiebreak favours a more specific major/minor match and then a range carrying more parameters.- Parameters:
ranges (tuple[MediaRange, Ellipsis]) – The parsed media ranges to select among.
major (str) – The response major type to match.
minor (str) – The response minor type to match.
parameters (collections.abc.Mapping[str, str]) – The response media-type parameters to match against.
- Returns:
The winning range’s quality, or
Nonewhen nothing matches.- Return type:
float | None
- httk.serve.http.http_parameter_value(value)[source]¶
Decode one token or quoted-string parameter value.
- httk.serve.http.parse_accept(header)[source]¶
Parse an
Acceptheader into its valid media ranges.- Parameters:
header (str) – The raw
Acceptheader value.- Returns:
The valid parsed media ranges, or
()when the header cannot be split.- Return type:
tuple[MediaRange, Ellipsis]
- httk.serve.http.parse_media_type(value)[source]¶
Parse a JSON media type into its major, minor, and parameters.
- httk.serve.http.split_http_list(value, delimiter)[source]¶
Split an HTTP field outside quoted strings, rejecting broken quoting.
- type httk.serve.http.JsonDocumentFactory = Callable[[], JsonDocument | Awaitable[JsonDocument]][source]¶
- httk.serve.http.create_file_map_app(files, *, debug=False)[source]¶
Create an application exposing only explicitly mapped files.
- Parameters:
files (collections.abc.Mapping[str, str | pathlib.Path]) – Root-relative URL paths mapped to filesystem paths.
debug (bool) – Whether Starlette debug responses are enabled.
- Returns:
A mountable application serving the declared files.
- Return type:
- httk.serve.http.json_get_app(document, *, path='/', media_type='application/json', profile=None, cache_control='public, max-age=60', cors_allow_origin='*', debug=False)[source]¶
Create a lightweight application serving one live JSON document.
- Parameters:
document (JsonDocument | JsonDocumentFactory) – JSON mapping or live zero-argument document factory.
path (str) – Canonical root-relative route, normally
/for mounting.media_type (str) – JSON response media type, including optional parameters.
profile (str | None) – Optional profile IRI emitted as an RFC 6906
Linkheader.cache_control (str | None) – Optional
Cache-Controlresponse value.cors_allow_origin (str | None) – Optional
Access-Control-Allow-Originvalue.debug (bool) – Whether Starlette debug responses are enabled.
- Returns:
A mountable application serving the declared JSON resource.
- Return type:
- httk.serve.http.jsonld_get_app(document, *, path='/', media_type='application/ld+json', profile=None, cache_control='public, max-age=60', cors_allow_origin='*', debug=False)[source]¶
Create a lightweight application serving one live JSON-LD document.
- Parameters:
document (JsonDocument | JsonDocumentFactory) – JSON-LD mapping or live zero-argument document factory.
path (str) – Canonical root-relative route, normally
/for mounting.media_type (str) – JSON-LD response media type, including optional parameters.
profile (str | None) – Optional profile IRI emitted as an RFC 6906
Linkheader.cache_control (str | None) – Optional
Cache-Controlresponse value.cors_allow_origin (str | None) – Optional
Access-Control-Allow-Originvalue.debug (bool) – Whether Starlette debug responses are enabled.
- Returns:
A mountable application serving the declared JSON-LD resource.
- Return type:
- type httk.serve.http.ResponseHook = Callable[[], Awaitable[None]][source]¶
A zero-argument coroutine callback run once, after the response has been sent.
- type httk.serve.http.ServeApp = Starlette[source]¶
The httk-serve serving application type (a Starlette app; branded so consumers need not import Starlette).
Annotation-only: this is a type alias, not the
Starletteclass, so useStarletteitself forisinstance/subclass checks.
- httk.serve.http.is_field_name(value)[source]¶
Report whether a value is a valid RFC 9110 field name.
- httk.serve.http.is_field_value(value)[source]¶
Report whether a value is an acceptable HTTP field value.
- httk.serve.http.validated_headers(pairs)[source]¶
Validate response header name-value pairs, rejecting duplicate names.
Names must be RFC 9110 field names and values must be non-empty and free of CR and LF; header names are compared case-insensitively for uniqueness.
- httk.serve.http.is_json_encodable_text(value)[source]¶
Report whether a string is free of lone UTF-16 surrogate code points.
- httk.serve.http.urn_uuid(value)[source]¶
Normalise a UUID factory result to the required
urn:uuid:URN form.- Parameters:
value (object) – UUID factory output rendered to text before normalisation.
- Returns:
The identifier in
urn:uuid:form.- Raises:
RuntimeError – If the rendered value is blank or contains a lone surrogate.
- Return type:
- httk.serve.http.xsd_utc_timestamp(value)[source]¶
Render a timezone-aware datetime as an XSD/RFC 3339 UTC timestamp.
- Parameters:
value (datetime.datetime) – Timezone-aware datetime to render as a UTC XML Schema date-time.
- Returns:
The value in UTC with a
Zsuffix.- Raises:
ValueError – If
valueis naive or lacks a UTC offset.
- Return type:
- class httk.serve.http.PinnedHttpsJsonPoster(*, connect_timeout=5.0, read_timeout=10.0, dns_timeout=5.0, total_timeout=20.0, response_body_limit=65536, max_concurrency=8, allow_private_addresses=False, resolver=None, connector=None)[source]¶
Send one HTTPS JSON POST through a validated, pinned socket.
DNS resolution occurs inside the concurrency cap and produces the exact numeric socket address dialed for the request. TLS SNI and the HTTP
Hostheader retain the original DNS hostname. The stdlib transport does not consult proxy or environment settings; redirects are not implemented. Both DNS and the complete operation have finite deadlines.- Parameters:
connect_timeout (float) – Maximum seconds for TCP connect and TLS handshake.
read_timeout (float) – Maximum seconds for reading a complete response body.
dns_timeout (float) – Maximum seconds for DNS resolution.
total_timeout (float) – Maximum seconds from the start of resolution through response completion.
response_body_limit (int) – Maximum response bytes consumed before rejection.
max_concurrency (int) – Maximum simultaneous resolution and send operations.
allow_private_addresses (bool) – Skip global-address filtering when
True; the default rejects private targets.resolver (_Resolver | None) – Optional test seam that resolves public pinned addresses.
connector (_Connector | None) – Optional test seam that dials a supplied pinned address.
- exception httk.serve.http.WebhookTransportError(detail)[source]¶
Bases:
RuntimeErrorRepresent an outbound webhook transport or URL-policy failure.
- Parameters:
detail (str) – Safe detail suitable for local process-delivery state.
- detail¶
- async httk.serve.http.deliver_with_retries(sender, url, document, *, attempts=2)[source]¶
Deliver a document through a sender at most
attemptstimes, requiring a 2xx status.- Parameters:
sender (WebhookSender) – Awaitable sender returning a peer HTTP status code.
url (str) – Complete webhook URL passed to the sender.
document (dict[str, httk.serve.jsondata.JsonValue]) – Plain JSON message document passed to the sender.
attempts (int) – Maximum number of delivery attempts before failing.
- Raises:
WebhookTransportError – If no attempt yields a 2xx acknowledgement.
- httk.serve.http.join_url_path(base_url, path)[source]¶
Append a fixed absolute path without depending on a trailing slash.
- Parameters:
- Returns:
Complete URL.
- Raises:
ValueError – If the base or fixed path is malformed.
- Return type: