Skip to content
Myr

datastructures.py

This file

Path

httpcore/datastructures.py

284 lines · 8.4 KiB · Python

Last changed by

Add SyncConnectionPoolTom Christiebefore adoption4a36ec7

History of this file

Take it

1import http2import typing3from types import TracebackType4from urllib.parse import urlsplit56from .config import SSLConfig, TimeoutConfig7from .decoders import (8    ACCEPT_ENCODING,9    SUPPORTED_DECODERS,10    Decoder,11    IdentityDecoder,12    MultiDecoder,13)14from .exceptions import ResponseClosed, StreamConsumed151617class URL:18    def __init__(self, url: str = "") -> None:19        self.components = urlsplit(url)20        if not self.components.scheme:21            raise ValueError("No scheme included in URL.")22        if self.components.scheme not in ("http", "https"):23            raise ValueError('URL scheme must be "http" or "https".')24        if not self.components.hostname:25            raise ValueError("No hostname included in URL.")2627    @property28    def scheme(self) -> str:29        return self.components.scheme3031    @property32    def netloc(self) -> str:33        return self.components.netloc3435    @property36    def path(self) -> str:37        return self.components.path3839    @property40    def query(self) -> str:41        return self.components.query4243    @property44    def hostname(self) -> str:45        return self.components.hostname4647    @property48    def port(self) -> int:49        port = self.components.port50        if port is None:51            return {"https": 443, "http": 80}[self.scheme]52        return port5354    @property55    def target(self) -> str:56        path = self.path or "/"57        query = self.query58        if query:59            return path + "?" + query60        return path6162    @property63    def is_secure(self) -> bool:64        return self.components.scheme == "https"6566    @property67    def origin(self) -> "Origin":68        return Origin(self)697071class Origin:72    def __init__(self, url: typing.Union[str, URL]) -> None:73        if isinstance(url, str):74            url = URL(url)75        self.scheme = url.scheme76        self.hostname = url.hostname77        self.port = url.port7879    @property80    def is_secure(self) -> bool:81        return self.scheme == "https"8283    def __eq__(self, other: typing.Any) -> bool:84        return (85            isinstance(other, self.__class__)86            and self.scheme == other.scheme87            and self.hostname == other.hostname88            and self.port == other.port89        )9091    def __hash__(self) -> int:92        return hash((self.scheme, self.hostname, self.port))939495class Request:96    def __init__(97        self,98        method: str,99        url: typing.Union[str, URL],100        *,101        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),102        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",103    ):104        self.method = method.upper()105        self.url = URL(url) if isinstance(url, str) else url106        self.headers = list(headers)107        if isinstance(body, bytes):108            self.is_streaming = False109            self.body = body110        else:111            self.is_streaming = True112            self.body_aiter = body113        self.headers = self._auto_headers() + self.headers114115    def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:116        has_host = False117        has_content_length = False118        has_accept_encoding = False119120        for header, value in self.headers:121            header = header.strip().lower()122            if header == b"host":123                has_host = True124            elif header in (b"content-length", b"transfer-encoding"):125                has_content_length = True126            elif header == b"accept-encoding":127                has_accept_encoding = True128129        headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]130131        if not has_host:132            headers.append((b"host", self.url.netloc.encode("ascii")))133        if not has_content_length:134            if self.is_streaming:135                headers.append((b"transfer-encoding", b"chunked"))136            elif self.body:137                content_length = str(len(self.body)).encode()138                headers.append((b"content-length", content_length))139        if not has_accept_encoding:140            headers.append((b"accept-encoding", ACCEPT_ENCODING))141142        return headers143144    async def stream(self) -> typing.AsyncIterator[bytes]:145        assert self.is_streaming146147        async for part in self.body_aiter:148            yield part149150151class Response:152    def __init__(153        self,154        status_code: int,155        *,156        reason: typing.Optional[str] = None,157        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),158        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",159        on_close: typing.Callable = None,160    ):161        self.status_code = status_code162        if not reason:163            try:164                self.reason = http.HTTPStatus(status_code).phrase165            except ValueError as exc:166                self.reason = ""167        else:168            self.reason = reason169        self.headers = list(headers)170        self.on_close = on_close171        self.is_closed = False172        self.is_streamed = False173174        decoders = []  # type: typing.List[Decoder]175        for header, value in self.headers:176            if header.strip().lower() == b"content-encoding":177                for part in value.split(b","):178                    part = part.strip().lower()179                    decoder_cls = SUPPORTED_DECODERS[part]180                    decoders.append(decoder_cls())181182        if len(decoders) == 0:183            self.decoder = IdentityDecoder()  # type: Decoder184        elif len(decoders) == 1:185            self.decoder = decoders[0]186        else:187            self.decoder = MultiDecoder(decoders)188189        if isinstance(body, bytes):190            self.is_closed = True191            self.body = self.decoder.decode(body) + self.decoder.flush()192        else:193            self.body_aiter = body194195    async def read(self) -> bytes:196        """197        Read and return the response content.198        """199        if not hasattr(self, "body"):200            body = b""201            async for part in self.stream():202                body += part203            self.body = body204        return self.body205206    async def stream(self) -> typing.AsyncIterator[bytes]:207        """208        A byte-iterator over the decoded response content.209        This allows us to handle gzip, deflate, and brotli encoded responses.210        """211        if hasattr(self, "body"):212            yield self.body213        else:214            async for chunk in self.raw():215                yield self.decoder.decode(chunk)216            yield self.decoder.flush()217218    async def raw(self) -> typing.AsyncIterator[bytes]:219        """220        A byte-iterator over the raw response content.221        """222        if self.is_streamed:223            raise StreamConsumed()224        if self.is_closed:225            raise ResponseClosed()226        self.is_streamed = True227        async for part in self.body_aiter:228            yield part229        await self.close()230231    async def close(self) -> None:232        """233        Close the response and release the connection.234        Automatically called if the response body is read to completion.235        """236        if not self.is_closed:237            self.is_closed = True238            if self.on_close is not None:239                await self.on_close()240241242class Client:243    async def request(244        self,245        method: str,246        url: typing.Union[str, URL],247        *,248        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),249        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",250        ssl: typing.Optional[SSLConfig] = None,251        timeout: typing.Optional[TimeoutConfig] = None,252        stream: bool = False,253    ) -> Response:254        request = Request(method, url, headers=headers, body=body)255        response = await self.send(request, ssl=ssl, timeout=timeout)256        if not stream:257            try:258                await response.read()259            finally:260                await response.close()261        return response262263    async def send(264        self,265        request: Request,266        *,267        ssl: typing.Optional[SSLConfig] = None,268        timeout: typing.Optional[TimeoutConfig] = None,269    ) -> Response:270        raise NotImplementedError()  # pragma: nocover271272    async def close(self) -> None:273        raise NotImplementedError()  # pragma: nocover274275    async def __aenter__(self) -> "Client":276        return self277278    async def __aexit__(279        self,280        exc_type: typing.Type[BaseException] = None,281        exc_value: BaseException = None,282        traceback: TracebackType = None,283    ) -> None:284        await self.close()