Skip to content

Handlers

Response handler factories. See the Response handlers guide for usage.

asyncly.client.handlers.json.parse_json

parse_json(
    parser: Callable, loads: Callable = loads
) -> Callable[[ClientResponse], Awaitable[Any]]

Build a response handler that decodes JSON and passes it to parser.

Parameters:

Name Type Description Default
parser Callable

Callable applied to the decoded JSON. May be sync or async. Use lambda data: data to return the parsed value unchanged.

required
loads Callable

JSON loader. Defaults to orjson.loads when the orjson extra is installed, otherwise the stdlib json.loads.

loads

Returns:

Type Description
Callable[[ClientResponse], Awaitable[Any]]

An async handler usable as a value in a response-handlers mapping.

Source code in asyncly/client/handlers/json.py
def parse_json(
    parser: Callable,
    loads: Callable = json.loads,
) -> Callable[[ClientResponse], Awaitable[Any]]:
    """Build a response handler that decodes JSON and passes it to ``parser``.

    Args:
        parser: Callable applied to the decoded JSON. May be sync or async.
            Use ``lambda data: data`` to return the parsed value unchanged.
        loads: JSON loader. Defaults to `orjson.loads` when the ``orjson``
            extra is installed, otherwise the stdlib `json.loads`.

    Returns:
        An async handler usable as a value in a response-handlers mapping.
    """

    async def _parse(response: ClientResponse) -> Any:
        response_data = await response.json(loads=loads)
        if iscoroutinefunction(parser):
            return await parser(response_data)
        else:
            return parser(response_data)

    return _parse

asyncly.client.handlers.pydantic.parse_model

parse_model(
    model: type[T],
) -> Callable[[ClientResponse], Awaitable[T]]

Build a response handler that validates the body into a Pydantic model.

Requires the pydantic extra.

Parameters:

Name Type Description Default
model type[T]

The pydantic.BaseModel subclass to validate the JSON body into.

required

Returns:

Type Description
Callable[[ClientResponse], Awaitable[T]]

An async handler usable as a value in a response-handlers mapping.

Raises:

Type Description
ValidationError

If the body does not match the model.

Source code in asyncly/client/handlers/pydantic.py
def parse_model(model: type[T]) -> Callable[[ClientResponse], Awaitable[T]]:
    """Build a response handler that validates the body into a Pydantic model.

    Requires the ``pydantic`` extra.

    Args:
        model: The `pydantic.BaseModel` subclass to validate the JSON body into.

    Returns:
        An async handler usable as a value in a response-handlers mapping.

    Raises:
        pydantic.ValidationError: If the body does not match the model.
    """

    async def _parse(response: ClientResponse) -> T:
        return model.model_validate_json(await response.read())

    return _parse

asyncly.client.handlers.msgspec.parse_struct

parse_struct(
    struct: type[T],
    data_format: DataFormat = "json",
    strict: bool = True,
) -> Callable[[ClientResponse], Awaitable[T]]

Build a response handler that decodes the body into a msgspec struct.

Requires the msgspec extra.

Parameters:

Name Type Description Default
struct type[T]

The msgspec.Struct subclass to decode into.

required
data_format DataFormat

Wire format of the body: "json", "msgpack", "toml", or "yaml".

'json'
strict bool

Pass-through to msgspec strict decoding (no implicit coercion).

True

Returns:

Type Description
Callable[[ClientResponse], Awaitable[T]]

An async handler usable as a value in a response-handlers mapping.

Raises:

Type Description
ValidationError

If the payload does not match struct.

Source code in asyncly/client/handlers/msgspec.py
def parse_struct(
    struct: type[T],
    data_format: DataFormat = "json",
    strict: bool = True,
) -> Callable[[ClientResponse], Awaitable[T]]:
    """Build a response handler that decodes the body into a msgspec struct.

    Requires the ``msgspec`` extra.

    Args:
        struct: The `msgspec.Struct` subclass to decode into.
        data_format: Wire format of the body: ``"json"``, ``"msgpack"``,
            ``"toml"``, or ``"yaml"``.
        strict: Pass-through to msgspec strict decoding (no implicit coercion).

    Returns:
        An async handler usable as a value in a response-handlers mapping.

    Raises:
        msgspec.ValidationError: If the payload does not match ``struct``.
    """
    decode = _choose_decoder(data_format)

    async def _parse(response: ClientResponse) -> T:
        return decode(await response.read(), type=struct, strict=strict)

    return _parse

Exceptions

asyncly.client.handlers.exceptions.UnhandledStatusException

UnhandledStatusException(
    message: str,
    status: int,
    url: URL,
    client_name: str | None = None,
)

Bases: BaseHttpClientException, KeyError

Raised when a response status has no matching handler.

Attributes:

Name Type Description
status int

The unmatched response status code.

url URL

The request URL.

client_name str | None

The originating client's name, if known.

Source code in asyncly/client/handlers/exceptions.py
def __init__(
    self,
    message: str,
    status: int,
    url: URL,
    client_name: str | None = None,
):
    super().__init__(message)
    self.status = status
    self.url = url
    self.client_name = client_name

asyncly.client.handlers.exceptions.BaseHttpClientException

Bases: ClientError

Base class for exceptions raised by BaseHttpClient.