Skip to content

HttpSession

🛈 DocStrings

One httpx client for many requests (connection reuse); see http_session.

base_url resolves relative URLs. The session's headers go with requests to base_url (relative URLs and absolute ones under it); without a base_url, with every request through the session, including those of libraries that use anyenv's helpers inside the async with block.

Source code in src/anyenv/download/session.py
class HttpSession:
    """One httpx client for many requests (connection reuse); see `http_session`.

    ``base_url`` resolves relative URLs. The session's ``headers`` go with requests
    to ``base_url`` (relative URLs and absolute ones under it); without a
    ``base_url``, with every request through the session, including those of
    libraries that use anyenv's helpers inside the ``async with`` block.
    """

    def __init__(
        self,
        *,
        base_url: str | None = None,
        headers: HeaderType | None = None,
        cache: CacheSettings | None = None,
        timeout: float | None = _UNSET,
    ) -> None:
        self.base_url = base_url
        self.headers: HeaderType = dict(headers or {})
        self.cache = cache or CacheSettings.create(False)
        self.timeout: float | None = DEFAULT_TIMEOUT if timeout is _UNSET else timeout
        self._timeout_arg: float | None = timeout
        self._client, self._httpx = create_client(self.cache, timeout)
        self._closed = False
        self._loop: asyncio.AbstractEventLoop | None = None

    @property
    def closed(self) -> bool:
        """Whether the session's client was closed."""
        return self._closed

    async def aclose(self) -> None:
        """Close the client (and its connections)."""
        self._closed = True
        self._loop = None  # no reference that keeps a finished loop alive
        await self._client.aclose()

    async def __aenter__(self) -> Self:
        self._loop = asyncio.get_running_loop()
        return self

    async def __aexit__(self, *exc_info: object) -> None:
        await self.aclose()

    def usable_here(self) -> bool:
        """Whether this context can use the client: it's open and on its event loop.

        (Another loop may see the session through a copied context, e.g. in
        ``run_sync``; a client can't be shared between loops.)
        """
        if self._closed:
            return False
        try:
            loop = asyncio.get_running_loop()
        except RuntimeError:
            return False
        return self._loop is None or self._loop is loop

    def accepts(
        self,
        cache: bool | None,
        cache_dir: StrPath | None,
        cache_ttl: int | str | None,
    ) -> bool:
        """Whether a helper call with these cache options can go through this session."""
        if self._closed:
            return False
        if cache is not None and cache != self.cache.enabled:
            return False
        if cache_dir is not None and pathlib.Path(cache_dir) != self.cache.directory:
            return False
        return cache_ttl is None or parse_ttl(cache_ttl) == self.cache.ttl

    def resolve(self, url: str) -> str:
        """The absolute URL of a request (relative URLs are appended to ``base_url``)."""
        if self.base_url is None or _is_absolute(url):
            return url
        return f"{self.base_url.rstrip('/')}/{url.lstrip('/')}"

    def _under_base_url(self, url: str) -> bool:
        if self.base_url is None:
            return True
        base = self.base_url.rstrip("/")
        return url == base or url.startswith((f"{base}/", f"{base}?"))

    def _headers_for(self, url: str, headers: HeaderType | None) -> HeaderType:
        own = self.headers if self._under_base_url(url) else {}
        return header_middlewares.apply(url, {**own, **(headers or {})})

    async def request(
        self,
        method: Method,
        url: str,
        *,
        json: Any = None,
        data: Any = None,
        files: FilesType | None = None,
        **options: Unpack[RequestOptions],
    ) -> HttpResponse:
        """Send a request; returns the response once its body is read.

        Raises:
            RequestError: The request failed (connection, timeout)
            ResponseError: The response has a 4xx / 5xx status
        """
        url = self.resolve(url)
        headers, params = apply_auth(
            self._headers_for(url, options.get("headers")),
            options.get("params"),
            api_key=options.get("api_key"),
            auth_type=options.get("auth_type", "bearer"),
            auth_username=options.get("auth_username"),
            auth_header_name=options.get("auth_header_name"),
        )
        extra: dict[str, Any] = {}
        if "timeout" in options and options["timeout"] is not _UNSET:
            extra["timeout"] = options["timeout"]
        try:
            response = await self._client.request(
                method,
                url,
                params=params,
                headers=headers,
                json=json,
                data=data,
                files=files,
                **extra,
            )
        except self._httpx.RequestError as exc:
            msg = f"Request failed: {exc!s}"
            raise RequestError(msg) from exc
        return check_response(HttpResponse(response))

    async def get(self, url: str, **options: Unpack[RequestOptions]) -> HttpResponse:
        """Send a GET request."""
        return await self.request("GET", url, **options)

    async def post(
        self,
        url: str,
        *,
        json: Any = None,
        data: Any = None,
        files: FilesType | None = None,
        **options: Unpack[RequestOptions],
    ) -> HttpResponse:
        """Send a POST request."""
        return await self.request("POST", url, json=json, data=data, files=files, **options)

    async def get_text(self, url: str, **options: Unpack[RequestOptions]) -> str:
        """GET a URL and return the body as text."""
        return (await self.get(url, **options)).text

    async def get_bytes(self, url: str, **options: Unpack[RequestOptions]) -> bytes:
        """GET a URL and return the body as bytes."""
        return (await self.get(url, **options)).content

    async def get_json[T](
        self, url: str, *, return_type: type[T] | None = None, **options: Unpack[RequestOptions]
    ) -> T:
        """GET a URL and return the body parsed as JSON (validated if `return_type`)."""
        from anyenv.validate import validate_json_data

        return validate_json_data((await self.get(url, **options)).json(), return_type)

    async def post_json[T](
        self,
        url: str,
        json_data: Any,
        *,
        files: FilesType | None = None,
        return_type: type[T] | None = None,
        **options: Unpack[RequestOptions],
    ) -> T:
        """POST JSON (form data with `files`) and return the response parsed as JSON."""
        from anyenv.validate import validate_json_data

        if files:
            response = await self.post(url, data=json_data, files=files, **options)
        else:
            response = await self.post(url, json=json_data, **options)
        return validate_json_data(response.json(), return_type)

    async def download(
        self,
        url: str,
        path: StrPath,
        *,
        headers: HeaderType | None = None,
        progress_callback: ProgressCallback | None = None,
        timeout: float | None = _UNSET,
    ) -> None:
        """Stream a URL into a file (``<path>.part`` until complete).

        The read timeout applies per read (not to the whole download), so large
        downloads keep working as long as data keeps arriving; pass
        ``timeout=None`` to disable timeouts altogether.
        """
        url = self.resolve(url)
        extra: dict[str, Any] = {} if timeout is _UNSET else {"timeout": timeout}
        try:
            async with self._client.stream(
                "GET", url, headers=self._headers_for(url, headers), **extra
            ) as response:
                if 400 <= response.status_code < 600:  # noqa: PLR2004
                    await response.aread()
                    message = f"HTTP Error {response.status_code}"
                    raise ResponseError(message, HttpResponse(response))
                total = int(response.headers.get("content-length", "0"))
                current = 0
                with open_download_target(path) as f:
                    async for chunk in response.aiter_bytes():
                        f.write(chunk)
                        current += len(chunk)
                        if progress_callback:
                            result = progress_callback(current, total)
                            if inspect.isawaitable(result):
                                await result
        except self._httpx.RequestError as exc:
            msg = f"Download failed: {exc!s}"
            raise RequestError(msg) from exc

closed property

closed: bool

Whether the session's client was closed.

accepts

accepts(cache: bool | None, cache_dir: StrPath | None, cache_ttl: int | str | None) -> bool

Whether a helper call with these cache options can go through this session.

Source code in src/anyenv/download/session.py
def accepts(
    self,
    cache: bool | None,
    cache_dir: StrPath | None,
    cache_ttl: int | str | None,
) -> bool:
    """Whether a helper call with these cache options can go through this session."""
    if self._closed:
        return False
    if cache is not None and cache != self.cache.enabled:
        return False
    if cache_dir is not None and pathlib.Path(cache_dir) != self.cache.directory:
        return False
    return cache_ttl is None or parse_ttl(cache_ttl) == self.cache.ttl

aclose async

aclose() -> None

Close the client (and its connections).

Source code in src/anyenv/download/session.py
async def aclose(self) -> None:
    """Close the client (and its connections)."""
    self._closed = True
    self._loop = None  # no reference that keeps a finished loop alive
    await self._client.aclose()

download async

download(
    url: str,
    path: StrPath,
    *,
    headers: HeaderType | None = None,
    progress_callback: ProgressCallback | None = None,
    timeout: float | None = _UNSET,
) -> None

Stream a URL into a file (<path>.part until complete).

The read timeout applies per read (not to the whole download), so large downloads keep working as long as data keeps arriving; pass timeout=None to disable timeouts altogether.

Source code in src/anyenv/download/session.py
async def download(
    self,
    url: str,
    path: StrPath,
    *,
    headers: HeaderType | None = None,
    progress_callback: ProgressCallback | None = None,
    timeout: float | None = _UNSET,
) -> None:
    """Stream a URL into a file (``<path>.part`` until complete).

    The read timeout applies per read (not to the whole download), so large
    downloads keep working as long as data keeps arriving; pass
    ``timeout=None`` to disable timeouts altogether.
    """
    url = self.resolve(url)
    extra: dict[str, Any] = {} if timeout is _UNSET else {"timeout": timeout}
    try:
        async with self._client.stream(
            "GET", url, headers=self._headers_for(url, headers), **extra
        ) as response:
            if 400 <= response.status_code < 600:  # noqa: PLR2004
                await response.aread()
                message = f"HTTP Error {response.status_code}"
                raise ResponseError(message, HttpResponse(response))
            total = int(response.headers.get("content-length", "0"))
            current = 0
            with open_download_target(path) as f:
                async for chunk in response.aiter_bytes():
                    f.write(chunk)
                    current += len(chunk)
                    if progress_callback:
                        result = progress_callback(current, total)
                        if inspect.isawaitable(result):
                            await result
    except self._httpx.RequestError as exc:
        msg = f"Download failed: {exc!s}"
        raise RequestError(msg) from exc

get async

get(url: str, **options: Unpack[RequestOptions]) -> HttpResponse

Send a GET request.

Source code in src/anyenv/download/session.py
async def get(self, url: str, **options: Unpack[RequestOptions]) -> HttpResponse:
    """Send a GET request."""
    return await self.request("GET", url, **options)

get_bytes async

get_bytes(url: str, **options: Unpack[RequestOptions]) -> bytes

GET a URL and return the body as bytes.

Source code in src/anyenv/download/session.py
async def get_bytes(self, url: str, **options: Unpack[RequestOptions]) -> bytes:
    """GET a URL and return the body as bytes."""
    return (await self.get(url, **options)).content

get_json async

get_json(
    url: str, *, return_type: type[T] | None = None, **options: Unpack[RequestOptions]
) -> T

GET a URL and return the body parsed as JSON (validated if return_type).

Source code in src/anyenv/download/session.py
async def get_json[T](
    self, url: str, *, return_type: type[T] | None = None, **options: Unpack[RequestOptions]
) -> T:
    """GET a URL and return the body parsed as JSON (validated if `return_type`)."""
    from anyenv.validate import validate_json_data

    return validate_json_data((await self.get(url, **options)).json(), return_type)

get_text async

get_text(url: str, **options: Unpack[RequestOptions]) -> str

GET a URL and return the body as text.

Source code in src/anyenv/download/session.py
async def get_text(self, url: str, **options: Unpack[RequestOptions]) -> str:
    """GET a URL and return the body as text."""
    return (await self.get(url, **options)).text

post async

post(
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **options: Unpack[RequestOptions],
) -> HttpResponse

Send a POST request.

Source code in src/anyenv/download/session.py
async def post(
    self,
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **options: Unpack[RequestOptions],
) -> HttpResponse:
    """Send a POST request."""
    return await self.request("POST", url, json=json, data=data, files=files, **options)

post_json async

post_json(
    url: str,
    json_data: Any,
    *,
    files: FilesType | None = None,
    return_type: type[T] | None = None,
    **options: Unpack[RequestOptions],
) -> T

POST JSON (form data with files) and return the response parsed as JSON.

Source code in src/anyenv/download/session.py
async def post_json[T](
    self,
    url: str,
    json_data: Any,
    *,
    files: FilesType | None = None,
    return_type: type[T] | None = None,
    **options: Unpack[RequestOptions],
) -> T:
    """POST JSON (form data with `files`) and return the response parsed as JSON."""
    from anyenv.validate import validate_json_data

    if files:
        response = await self.post(url, data=json_data, files=files, **options)
    else:
        response = await self.post(url, json=json_data, **options)
    return validate_json_data(response.json(), return_type)

request async

request(
    method: Method,
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **options: Unpack[RequestOptions],
) -> HttpResponse

Send a request; returns the response once its body is read.

Raises:

Type Description
RequestError

The request failed (connection, timeout)

ResponseError

The response has a 4xx / 5xx status

Source code in src/anyenv/download/session.py
async def request(
    self,
    method: Method,
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **options: Unpack[RequestOptions],
) -> HttpResponse:
    """Send a request; returns the response once its body is read.

    Raises:
        RequestError: The request failed (connection, timeout)
        ResponseError: The response has a 4xx / 5xx status
    """
    url = self.resolve(url)
    headers, params = apply_auth(
        self._headers_for(url, options.get("headers")),
        options.get("params"),
        api_key=options.get("api_key"),
        auth_type=options.get("auth_type", "bearer"),
        auth_username=options.get("auth_username"),
        auth_header_name=options.get("auth_header_name"),
    )
    extra: dict[str, Any] = {}
    if "timeout" in options and options["timeout"] is not _UNSET:
        extra["timeout"] = options["timeout"]
    try:
        response = await self._client.request(
            method,
            url,
            params=params,
            headers=headers,
            json=json,
            data=data,
            files=files,
            **extra,
        )
    except self._httpx.RequestError as exc:
        msg = f"Request failed: {exc!s}"
        raise RequestError(msg) from exc
    return check_response(HttpResponse(response))

resolve

resolve(url: str) -> str

The absolute URL of a request (relative URLs are appended to base_url).

Source code in src/anyenv/download/session.py
def resolve(self, url: str) -> str:
    """The absolute URL of a request (relative URLs are appended to ``base_url``)."""
    if self.base_url is None or _is_absolute(url):
        return url
    return f"{self.base_url.rstrip('/')}/{url.lstrip('/')}"

usable_here

usable_here() -> bool

Whether this context can use the client: it's open and on its event loop.

(Another loop may see the session through a copied context, e.g. in run_sync; a client can't be shared between loops.)

Source code in src/anyenv/download/session.py
def usable_here(self) -> bool:
    """Whether this context can use the client: it's open and on its event loop.

    (Another loop may see the session through a copied context, e.g. in
    ``run_sync``; a client can't be shared between loops.)
    """
    if self._closed:
        return False
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        return False
    return self._loop is None or self._loop is loop

:fa-brands-github: Show source on GitHub