GitHub

response

API reference for response.

HTTP responses (Effect's HttpClientResponse).

A response has its request, status, headers and cookies at once; the body is read on demand, as bytes (bytes_), text, JSON, form parameters or a stream. Reading it as a whole once caches it, so text then json read the network once::

todo = yield from response.schema_body_json(Todo)(res)

make builds a response, for tests and for clients that are not backed by a network.

Re-exports

Types

TypeDefinitionDescription
ResponseBodytype ResponseBody = bytes | Stream[bytes, object] | None

A response body: all of it, a stream of it (read once), or none (a HEAD response, a 204).

StatusRangetype StatusRange = Literal['2xx', '3xx', '4xx', '5xx']

Classes

Functions

is_too_large

is_too_large(error) -> bool

Whether error is a with_body_limit read stopping at its limit.

ParameterTypeDescription
errorHttpClientError

Returns bool

def is_too_large(error: HttpClientError) -> bool:
    """Whether ``error`` is a ``with_body_limit`` read stopping at its limit."""
    return isinstance(error.reason, DecodeError) and isinstance(
        error.reason.cause, ResponseTooLargeError
    )

with_body_limit

with_body_limit(response, max_bytes) -> HttpClientResponse

response with a body that is read only until it passes max_bytes: then the read (bytes_, text, json, stream) stops and fails (is_too_large), and a declared content-length over the limit fails before anything is read. Use it for a server you do not control; response itself holds whatever the server sends.

ParameterTypeDescription
responseHttpClientResponse
max_bytesByteSize

Returns HttpClientResponse

def with_body_limit(response: HttpClientResponse, max_bytes: ByteSize) -> HttpClientResponse:
    """``response`` with a body that is read only until it passes
    ``max_bytes``: then the read (``bytes_``, ``text``, ``json``,
    ``stream``) stops and fails (``is_too_large``), and a declared
    ``content-length`` over the limit fails before anything is read. Use it
    for a server you do not control; ``response`` itself holds whatever
    the server sends."""
    return _LimitedResponse(response, max_bytes)

make

make(request, body=None, *, status=200, headers=None, url=None) -> HttpClientResponse

A response to request. A str body is sent as UTF-8; repeated set-cookie headers are kept apart when given as pairs or a list.

ParameterTypeDescription
requestHttpClientRequest
bodyResponseBody | str = None
statusint = 200
headersHeadersInput | None = None
urlstr | None = None

Returns HttpClientResponse

def make(
    request: HttpClientRequest,
    body: ResponseBody | str = None,
    *,
    status: int = 200,
    headers: HeadersInput | None = None,
    url: str | None = None,
) -> HttpClientResponse:
    """A response to ``request``. A ``str`` body is sent as UTF-8; repeated
    ``set-cookie`` headers are kept apart when given as pairs or a list."""
    data = text_encode(body) if isinstance(body, str) else body
    return HttpClientResponse(
        request,
        status,
        headers_from_input(headers),
        data,
        url=url,
        set_cookie=_set_cookie_values(headers),
    )

stream

stream[E, R](effect) -> Stream[bytes, HttpClientError | E, R]

The body stream of the response effect gives.

ParameterTypeDescription
effectEffect[HttpClientResponse, E, R]

Returns Stream[bytes, HttpClientError | E, R]

def stream[E, R](effect: Effect[HttpClientResponse, E, R]) -> Stream[bytes, HttpClientError | E, R]:
    """The body stream of the response ``effect`` gives."""
    require_effect(effect, "effect")
    return from_effect(effect).flat_map(lambda response: response.stream)

match_status

match_status[T](response, cases, or_else) -> T

The case of the exact status, else of its range ("2xx", ...), else or_else.

ParameterTypeDescription
responseHttpClientResponse
casesMapping[int | StatusRange, Callable[[HttpClientResponse], T]]
or_elseCallable[[HttpClientResponse], T]

Returns T

def match_status[T](
    response: HttpClientResponse,
    cases: Mapping[int | StatusRange, Callable[[HttpClientResponse], T]],
    or_else: Callable[[HttpClientResponse], T],
) -> T:
    """The case of the exact status, else of its range (``"2xx"``, ...),
    else ``or_else``."""
    status = response.status
    exact = cases.get(status)
    if exact is not None:
        return exact(response)
    for low, name in ((200, "2xx"), (300, "3xx"), (400, "4xx"), (500, "5xx")):
        handler = cases.get(cast("StatusRange", name))
        if low <= status < low + 100 and handler is not None:
            return handler(response)
    return or_else(response)

filter_status

filter_status(f) -> Callable[[HttpClientResponse], Effect[HttpClientResponse, HttpClientError]]

Fail with a StatusCodeError unless f(status).

ParameterTypeDescription
fCallable[[int], bool]

Returns Callable[[HttpClientResponse], Effect[HttpClientResponse, HttpClientError]]

def filter_status(
    f: Callable[[int], bool],
) -> Callable[[HttpClientResponse], Effect[HttpClientResponse, HttpClientError]]:
    """Fail with a ``StatusCodeError`` unless ``f(status)``."""

    def check(response: HttpClientResponse) -> Effect[HttpClientResponse, HttpClientError]:
        def run() -> Effect[HttpClientResponse, HttpClientError]:
            if f(response.status):
                return succeed(response)
            return fail(
                HttpClientError(
                    StatusCodeError(response.request, response, None, "invalid status code")
                )
            )

        return suspend(run)

    return check

filter_status_ok

filter_status_ok(response) -> Effect[HttpClientResponse, HttpClientError]

Fail with a StatusCodeError unless the status is 2xx.

ParameterTypeDescription
responseHttpClientResponse

Returns Effect[HttpClientResponse, HttpClientError]

def filter_status_ok(response: HttpClientResponse) -> Effect[HttpClientResponse, HttpClientError]:
    """Fail with a ``StatusCodeError`` unless the status is 2xx."""
    if 200 <= response.status < 300:
        return succeed(response)
    return fail(
        HttpClientError(StatusCodeError(response.request, response, None, "non 2xx status code"))
    )

schema_json

schema_json[T, RD](schema, *, reviver=None, **options) -> Callable[[HttpClientResponse], Effect[T, HttpClientError | SchemaError, RD]]

A decoder of {"status", "headers", "body"} (the JSON body) by schema.

ParameterTypeDescription
schemaCodec[T, object, RD, object]
reviverReviver | None = None
optionsUnpack[ParseOptions] = {}

Returns Callable[[HttpClientResponse], Effect[T, HttpClientError | SchemaError, RD]]

def schema_json[T, RD](
    schema: Codec[T, object, RD, object],
    *,
    reviver: Reviver | None = None,
    **options: Unpack[ParseOptions],
) -> Callable[[HttpClientResponse], Effect[T, HttpClientError | SchemaError, RD]]:
    """A decoder of ``{"status", "headers", "body"}`` (the JSON body) by
    ``schema``."""
    decode = decode_unknown_effect(to_codec_json(schema), **options)
    decode_body = schema_body_json(Unknown, reviver=reviver, **options)

    def run(response: HttpClientResponse) -> Effect[T, HttpClientError | SchemaError, RD]:
        return decode_body(response).flat_map(
            lambda body: decode(
                {"status": response.status, "headers": dict(response.headers), "body": body}
            )
        )

    return run

schema_no_body

schema_no_body[T, RD](schema, **options) -> Callable[[HttpClientResponse], Effect[T, SchemaError, RD]]

A decoder of {"status", "headers"} by schema.

ParameterTypeDescription
schemaCodec[T, object, RD, object]
optionsUnpack[ParseOptions] = {}

Returns Callable[[HttpClientResponse], Effect[T, SchemaError, RD]]

def schema_no_body[T, RD](
    schema: Codec[T, object, RD, object], **options: Unpack[ParseOptions]
) -> Callable[[HttpClientResponse], Effect[T, SchemaError, RD]]:
    """A decoder of ``{"status", "headers"}`` by ``schema``."""
    decode = decode_effect(schema, **options)
    return lambda response: decode({"status": response.status, "headers": dict(response.headers)})