Skip to content
Myr

api.py

This file

Path

httpcore/api.py

132 lines · 3.6 KiB · Python

Last changed by

StuffTom Christiebefore adoption30530d4

History of this file

Take it

1import typing2from types import TracebackType34from .config import (5    DEFAULT_POOL_LIMITS,6    DEFAULT_SSL_CONFIG,7    DEFAULT_TIMEOUT_CONFIG,8    PoolLimits,9    SSLConfig,10    TimeoutConfig,11)12from .exceptions import ResponseClosed, StreamConsumed131415async def request(16    method: str,17    url: str,18    *,19    headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),20    body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",21    stream: bool = False,22    ssl: SSLConfig = DEFAULT_SSL_CONFIG,23    timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24) -> "Response":25    async with PoolManager(ssl=ssl, timeout=timeout) as pool:26       return await pool.request(27           method=method, url=url, headers=headers, body=body, stream=stream28       )293031class PoolManager:32    def __init__(33        self,34        *,35        ssl: SSLConfig = DEFAULT_SSL_CONFIG,36        timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,37        limits: PoolLimits = DEFAULT_POOL_LIMITS,38    ):39        self.ssl = ssl40        self.timeout = timeout41        self.limits = limits42        self.is_closed = False4344    async def request(45        self,46        method: str,47        url: str,48        *,49        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),50        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",51        stream: bool = False,52    ) -> "Response":53        if stream:54            async def streaming_body():55                yield b"Hello, "56                yield b"world!"57            return Response(200, body=streaming_body)58        return Response(200, body=b"Hello, world!")5960    async def close(self) -> None:61        self.is_closed = True6263    async def __aenter__(self) -> "PoolManager":64        return self6566    async def __aexit__(67        self,68        exc_type: typing.Type[BaseException] = None,69        exc_value: BaseException = None,70        traceback: TracebackType = None,71    ) -> None:72        await self.close()737475class Response:76    def __init__(77        self,78        status_code: int,79        *,80        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),81        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",82        on_close: typing.Callable = None,83    ):84        self.status_code = status_code85        self.headers = list(headers)86        self.on_close = on_close87        self.is_closed = False88        self.is_streamed = False89        if isinstance(body, bytes):90            self.is_closed = True91            self.body = body92        else:93            self.body_aiter = body9495    async def read(self) -> bytes:96        if not hasattr(self, "body"):97            body = b""98            async for part in self.stream():99                body += part100            self.body = body101        return self.body102103    async def stream(self) -> typing.AsyncIterator[bytes]:104        if hasattr(self, "body"):105            yield self.body106        else:107            if self.is_streamed:108                raise StreamConsumed()109            if self.is_closed:110                raise ResponseClosed()111            self.is_streamed = True112            async for part in self.body_aiter():113                yield part114            await self.close()115116    async def close(self) -> None:117        if not self.is_closed:118            self.is_closed = True119            if self.on_close is not None:120                await self.on_close()121122    async def __aenter__(self) -> "Response":123        return self124125    async def __aexit__(126        self,127        exc_type: typing.Type[BaseException] = None,128        exc_value: BaseException = None,129        traceback: TracebackType = None,130    ) -> None:131        if not self.is_closed:132            await self.close()