Skip to content
Myr

datastructures.py

This file

Path

httpcore/datastructures.py

200 lines · 6.0 KiB · Python

Last changed by

Rejig response streaming/closingTom Christiebefore adoption63d73ad

History of this file

Take it

1import typing2from urllib.parse import urlsplit34from .decoders import (5    ACCEPT_ENCODING,6    SUPPORTED_DECODERS,7    Decoder,8    IdentityDecoder,9    MultiDecoder,10)11from .exceptions import ResponseClosed, StreamConsumed121314class URL:15    def __init__(self, url: str = "") -> None:16        self.components = urlsplit(url)17        if not self.components.scheme:18            raise ValueError("No scheme included in URL.")19        if self.components.scheme not in ("http", "https"):20            raise ValueError('URL scheme must be "http" or "https".')21        if not self.components.hostname:22            raise ValueError("No hostname included in URL.")2324    @property25    def scheme(self) -> str:26        return self.components.scheme2728    @property29    def netloc(self) -> str:30        return self.components.netloc3132    @property33    def path(self) -> str:34        return self.components.path3536    @property37    def query(self) -> str:38        return self.components.query3940    @property41    def hostname(self) -> str:42        return self.components.hostname4344    @property45    def port(self) -> int:46        port = self.components.port47        if port is None:48            return {"https": 443, "http": 80}[self.scheme]49        return port5051    @property52    def target(self) -> str:53        path = self.path or "/"54        query = self.query55        if query:56            return path + "?" + query57        return path5859    @property60    def is_secure(self) -> bool:61        return self.components.scheme == "https"626364class Request:65    def __init__(66        self,67        method: str,68        url: typing.Union[str, URL],69        *,70        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),71        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",72    ):73        self.method = method74        self.url = URL(url) if isinstance(url, str) else url75        self.headers = list(headers)76        if isinstance(body, bytes):77            self.is_streaming = False78            self.body = body79        else:80            self.is_streaming = True81            self.body_aiter = body82        self.headers = self._auto_headers() + self.headers8384    def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:85        has_host = False86        has_content_length = False87        has_accept_encoding = False8889        for header, value in self.headers:90            header = header.strip().lower()91            if header == b"host":92                has_host = True93            elif header in (b"content-length", b"transfer-encoding"):94                has_content_length = True95            elif header == b"accept-encoding":96                has_accept_encoding = True9798        headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]99100        if not has_host:101            headers.append((b"host", self.url.netloc.encode("ascii")))102        if not has_content_length:103            if self.is_streaming:104                headers.append((b"transfer-encoding", b"chunked"))105            elif self.body:106                content_length = str(len(self.body)).encode()107                headers.append((b"content-length", content_length))108        if not has_accept_encoding:109            headers.append((b"accept-encoding", ACCEPT_ENCODING))110111        return headers112113    async def stream(self) -> typing.AsyncIterator[bytes]:114        assert self.is_streaming115116        async for part in self.body_aiter:117            yield part118119120class Response:121    def __init__(122        self,123        status_code: int,124        *,125        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),126        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",127        on_close: typing.Callable = None,128    ):129        self.status_code = status_code130        self.headers = list(headers)131        self.on_close = on_close132        self.is_closed = False133        self.is_streamed = False134135        decoders = []  # type: typing.List[Decoder]136        for header, value in self.headers:137            if header.strip().lower() == b"content-encoding":138                for part in value.split(b","):139                    part = part.strip().lower()140                    decoder_cls = SUPPORTED_DECODERS[part]141                    decoders.append(decoder_cls())142143        if len(decoders) == 0:144            self.decoder = IdentityDecoder()  # type: Decoder145        elif len(decoders) == 1:146            self.decoder = decoders[0]147        else:148            self.decoder = MultiDecoder(decoders)149150        if isinstance(body, bytes):151            self.is_closed = True152            self.body = self.decoder.decode(body) + self.decoder.flush()153        else:154            self.body_aiter = body155156    async def read(self) -> bytes:157        """158        Read and return the response content.159        """160        if not hasattr(self, "body"):161            body = b""162            async for part in self.stream():163                body += part164            self.body = body165        return self.body166167    async def stream(self) -> typing.AsyncIterator[bytes]:168        """169        A byte-iterator over the decoded response content.170        This allows us to handle gzip, deflate, and brotli encoded responses.171        """172        if hasattr(self, "body"):173            yield self.body174        else:175            async for chunk in self.raw():176                yield self.decoder.decode(chunk)177            yield self.decoder.flush()178179    async def raw(self) -> typing.AsyncIterator[bytes]:180        """181        A byte-iterator over the raw response content.182        """183        if self.is_streamed:184            raise StreamConsumed()185        if self.is_closed:186            raise ResponseClosed()187        self.is_streamed = True188        async for part in self.body_aiter:189            yield part190        await self.close()191192    async def close(self) -> None:193        """194        Close the response and release the connection.195        Automatically called if the response body is read to completion.196        """197        if not self.is_closed:198            self.is_closed = True199            if self.on_close is not None:200                await self.on_close()