The request a server handles (Effect's HttpServerRequest).
A ServerRequest is its method, URL (url, as the router sees it,
and original_url, as received), headers, cookies, addresses, and its
body, read as bytes_, text, json, url_params_body,
stream, or as multipart parts (multipart_stream) and a persisted
form (multipart). A body is read once: every read after the first
gives the same bytes, and MaxBodySize bounds it (BodyTooLarge,
413). Handlers get the current request from the HttpServerRequest
service::
request = yield from HttpServerRequest()Re-exports#
- From
pyfect.http.incoming_message:MaxBodySize - From
pyfect.http.server_error:HttpServerError - From
pyfect.schema:SchemaError
Types#
| Type | Definition | Description |
|---|---|---|
RequestProtocol | type RequestProtocol = Literal['http', 'https'] |
Classes#
Functions#
remove_host#
remove_host(url) -> strThe path and query of a URL that may be absolute.
| Parameter | Type | Description |
|---|---|---|
url | str |
Returns str
def remove_host(url: str) -> str:
"""The path and query of a URL that may be absolute."""
if url.startswith("/"):
return url
start = url.find("//")
index = url.find("/", start + 2)
return "/" if index == -1 else url[index:]search_params_from_url#
search_params_from_url(url) -> dict[str, str | list[str]]The query of url: each name's value, or values when repeated.
| Parameter | Type | Description |
|---|---|---|
url | _url.Url |
Returns dict[str, str | list[str]]
def search_params_from_url(url: _url.Url) -> dict[str, str | list[str]]:
"""The query of ``url``: each name's value, or values when repeated."""
return UrlParams(url.search_params).to_record()to_url#
to_url(request) -> _url.Url | NoneThe request's full URL, from its host header (localhost
without one) and protocol; None when that is no valid URL, or the
host is no authority (so it cannot change the path or query).
| Parameter | Type | Description |
|---|---|---|
request | ServerRequest |
Returns _url.Url | None
def to_url(request: ServerRequest) -> _url.Url | None:
"""The request's full URL, from its ``host`` header (``localhost``
without one) and protocol; ``None`` when that is no valid URL, or the
host is no authority (so it cannot change the path or query)."""
authority = parse_authority(request.headers.get("host") or "localhost")
if authority is None:
return None
protocol = request.protocol or (
"https" if request.original_url[:6].lower() == "https:" else "http"
)
url = request.url
origin = parse_origin_form(url)
try:
if origin is not None:
return _url.parse(absolute_url(protocol, authority, origin))
return _url.parse(url, absolute_url(protocol, authority, ROOT))
except ValueError:
return Noneto_url_result#
to_url_result(request) -> Result[_url.Url, RequestParseError]| Parameter | Type | Description |
|---|---|---|
request | ServerRequest |
Returns Result[_url.Url, RequestParseError]
def to_url_result(request: ServerRequest) -> Result[_url.Url, RequestParseError]:
url = to_url(request)
if url is None:
return Err(RequestParseError(request, "Invalid URL"))
return Ok(url)read_limited#
read_limited[E](chunks, content_length, max_bytes) -> Effect[bytes, E | BodyTooLargeError | ValueError]The bytes of chunks; past max_bytes (or the declared
content_length) the read stops and fails.
| Parameter | Type | Description |
|---|---|---|
chunks | Stream[bytes, E] | |
content_length | int | None | |
max_bytes | int | None |
Returns Effect[bytes, E | BodyTooLargeError | ValueError]
def read_limited[E](
chunks: Stream[bytes, E], content_length: int | None, max_bytes: int | None
) -> Effect[bytes, E | BodyTooLargeError | ValueError]:
"""The bytes of ``chunks``; past ``max_bytes`` (or the declared
``content_length``) the read stops and fails."""
require_stream(chunks, "chunks")
if max_bytes is not None and content_length is not None and content_length > max_bytes:
return fail(BodyTooLargeError(max_bytes))
limit = content_length if content_length is not None else max_bytes
out = bytearray()
def add(chunk: bytes) -> Effect[None, BodyTooLargeError | ValueError]:
out.extend(chunk)
if limit is not None and len(out) > limit:
if max_bytes is not None and len(out) > max_bytes:
return fail(BodyTooLargeError(max_bytes))
return fail(
ValueError(f"Request body is longer than its content-length of {content_length}")
)
return succeed(None)
return chunks.run_for_each(add).map(lambda _: bytes(out))form_data_body#
form_data_body(request) -> _body.FormData | NoneThe form of a request made from a client request with a form body.
| Parameter | Type | Description |
|---|---|---|
request | ServerRequest |
Returns _body.FormData | None
def form_data_body(request: ServerRequest) -> _body.FormData | None:
"""The form of a request made from a client request with a form body."""
source = request.source
if not isinstance(source, HttpClientRequest):
return None
body = source.body
if isinstance(body, _body.FormData):
return body
if isinstance(body, _body.Raw) and isinstance(body.body, _body.FormData):
return body.body
return Nonefrom_client_request#
from_client_request(request) -> ServerRequestA server request made from request (its full URL as received).
| Parameter | Type | Description |
|---|---|---|
request | HttpClientRequest |
Returns ServerRequest
def from_client_request(request: HttpClientRequest) -> ServerRequest:
"""A server request made from ``request`` (its full URL as received)."""
url = request.to_url()
return ClientRequest(request, request.url if url is None else _url.href(url))to_client_request#
to_client_request(request) -> HttpClientRequestrequest as an HttpClientRequest to its full URL, streaming
its body.
| Parameter | Type | Description |
|---|---|---|
request | ServerRequest |
Returns HttpClientRequest
def to_client_request(request: ServerRequest) -> HttpClientRequest:
"""``request`` as an ``HttpClientRequest`` to its full URL, streaming
its body."""
body = _client_body(request)
headers = request.headers
if not isinstance(body, _body.Empty) and body.content_length is None:
headers = headers.remove("content-length")
url = to_url(request)
client = HttpClientRequest(request.method, "", EMPTY_URL_PARAMS, None, headers, body)
# A parsed URL gives its query to ``url_params`` and its fragment to ``hash``.
return client.set_url(request.url if url is None else url)is_multipart#
is_multipart(request) -> bool| Parameter | Type | Description |
|---|---|---|
request | ServerRequest |
Returns bool
def is_multipart(request: ServerRequest) -> bool:
content_type = request.headers.get("content-type", "")
return "multipart/form-data" in content_type.lower() or form_data_body(request) is not Noneschema_cookies#
schema_cookies[T, RD](schema, **options) -> Effect[T, SchemaError, RD | HttpServerRequest]The request's cookies decoded by schema.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[T, Any, RD, Any] | |
options | Unpack[ParseOptions] = {} |
Returns Effect[T, SchemaError, RD | HttpServerRequest]
def schema_cookies[T, RD](
schema: Codec[T, Any, RD, Any], **options: Unpack[ParseOptions]
) -> Effect[T, SchemaError, RD | HttpServerRequest]:
"""The request's cookies decoded by ``schema``."""
decode = decode_unknown_effect(schema, **options)
return HttpServerRequest().flat_map(lambda request: decode(dict(request.cookies)))schema_headers#
schema_headers[T, RD](schema, **options) -> Effect[T, SchemaError, RD | HttpServerRequest]The request's headers (lowercased names) decoded by schema.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[T, Any, RD, Any] | |
options | Unpack[ParseOptions] = {} |
Returns Effect[T, SchemaError, RD | HttpServerRequest]
def schema_headers[T, RD](
schema: Codec[T, Any, RD, Any], **options: Unpack[ParseOptions]
) -> Effect[T, SchemaError, RD | HttpServerRequest]:
"""The request's headers (lowercased names) decoded by ``schema``."""
decode = decode_unknown_effect(schema, **options)
return HttpServerRequest().flat_map(lambda request: decode(dict(request.headers)))schema_search_params#
schema_search_params[T, RD](schema, **options) -> Effect[T, SchemaError, RD | ParsedSearchParams]The query parameters decoded by schema.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[T, Any, RD, Any] | |
options | Unpack[ParseOptions] = {} |
Returns Effect[T, SchemaError, RD | ParsedSearchParams]
def schema_search_params[T, RD](
schema: Codec[T, Any, RD, Any], **options: Unpack[ParseOptions]
) -> Effect[T, SchemaError, RD | ParsedSearchParams]:
"""The query parameters decoded by ``schema``."""
decode = decode_unknown_effect(schema, **options)
return ParsedSearchParams().flat_map(lambda params: decode(dict(params)))schema_body_json#
schema_body_json[T, RD](schema, *, reviver=None, **options) -> Effect[T, HttpServerError | SchemaError, RD | HttpServerRequest]The JSON body decoded by schema.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[T, Any, RD, Any] | |
reviver | Reviver | None = None | |
options | Unpack[ParseOptions] = {} |
Returns Effect[T, HttpServerError | SchemaError, RD | HttpServerRequest]
def schema_body_json[T, RD](
schema: Codec[T, Any, RD, Any],
*,
reviver: Reviver | None = None,
**options: Unpack[ParseOptions],
) -> Effect[T, HttpServerError | SchemaError, RD | HttpServerRequest]:
"""The JSON body decoded by ``schema``."""
decode = incoming_message.schema_body_json(schema, reviver=reviver, **options)
return HttpServerRequest().flat_map(decode)schema_body_url_params#
schema_body_url_params[T, RD](schema, **options) -> Effect[T, HttpServerError | SchemaError, RD | HttpServerRequest]The form-encoded body decoded by schema.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[T, Any, RD, Any] | |
options | Unpack[ParseOptions] = {} |
Returns Effect[T, HttpServerError | SchemaError, RD | HttpServerRequest]
def schema_body_url_params[T, RD](
schema: Codec[T, Any, RD, Any], **options: Unpack[ParseOptions]
) -> Effect[T, HttpServerError | SchemaError, RD | HttpServerRequest]:
"""The form-encoded body decoded by ``schema``."""
decode = incoming_message.schema_body_url_params(schema, **options)
return HttpServerRequest().flat_map(decode)schema_body_multipart#
schema_body_multipart[T, RD](schema, **options) -> Effect[T, Any, RD | HttpServerRequest | Scope | FileSystem | Path]The multipart form decoded by schema (its files persisted).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[T, Any, RD, Any] | |
options | Unpack[ParseOptions] = {} |
Returns Effect[T, Any, RD | HttpServerRequest | Scope | FileSystem | Path]
def schema_body_multipart[T, RD](
schema: Codec[T, Any, RD, Any], **options: Unpack[ParseOptions]
) -> Effect[T, Any, RD | HttpServerRequest | Scope | FileSystem | Path]:
"""The multipart form decoded by ``schema`` (its files persisted)."""
decode = decode_unknown_effect(schema, **options)
return HttpServerRequest().flat_map(
lambda request: request.multipart.flat_map(lambda persisted: decode(dict(persisted)))
)schema_body_form#
schema_body_form[T, RD](schema, **options) -> Effect[T, Any, RD | HttpServerRequest | Scope | FileSystem | Path]A multipart or form-encoded body decoded by schema.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[T, Any, RD, Any] | |
options | Unpack[ParseOptions] = {} |
Returns Effect[T, Any, RD | HttpServerRequest | Scope | FileSystem | Path]
def schema_body_form[T, RD](
schema: Codec[T, Any, RD, Any], **options: Unpack[ParseOptions]
) -> Effect[T, Any, RD | HttpServerRequest | Scope | FileSystem | Path]:
"""A multipart or form-encoded body decoded by ``schema``."""
decode = decode_unknown_effect(schema, **options)
url_params = incoming_message.schema_body_url_params(schema, **options)
def read(request: ServerRequest) -> Effect[T, Any, Any]:
if is_multipart(request):
return request.multipart.flat_map(lambda persisted: decode(dict(persisted)))
return url_params(request)
return HttpServerRequest().flat_map(read)schema_body_form_json#
schema_body_form_json[T, RD](schema, *, reviver=None, **options) -> Callable[[str], Effect[T, Any, RD | HttpServerRequest | Scope | FileSystem | Path]]A decoder of the JSON text in a form field (multipart or
form-encoded) by schema, parsed with reviver.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[T, Any, RD, Any] | |
reviver | Reviver | None = None | |
options | Unpack[ParseOptions] = {} |
Returns Callable[[str], Effect[T, Any, RD | HttpServerRequest | Scope | FileSystem | Path]]
def schema_body_form_json[T, RD](
schema: Codec[T, Any, RD, Any],
*,
reviver: Reviver | None = None,
**options: Unpack[ParseOptions],
) -> Callable[[str], Effect[T, Any, RD | HttpServerRequest | Scope | FileSystem | Path]]:
"""A decoder of the JSON text in a form field (multipart or
form-encoded) by ``schema``, parsed with ``reviver``."""
from pyfect.http.multipart import schema_json
from_multipart = schema_json(schema, reviver=reviver, **options)
def field(name: str) -> Effect[T, Any, Any]:
def read(request: ServerRequest) -> Effect[T, Any, Any]:
if is_multipart(request):
return request.multipart.map_error(
lambda cause: HttpServerError(RequestParseError(request, None, cause))
).flat_map(lambda persisted: from_multipart(persisted, name))
return request.url_params_body.flat_map(
lambda params: from_multipart(cast("Persisted", params.to_record()), name)
)
return HttpServerRequest().flat_map(read)
return fieldOn This Page
Re-exportsTypesClassesFunctionsremove_hostsearch_params_from_urlto_urlto_url_resultread_limitedform_data_bodyfrom_client_requestto_client_requestis_multipartschema_cookiesschema_headersschema_search_paramsschema_body_jsonschema_body_url_paramsschema_body_multipartschema_body_formschema_body_form_json