Skip to content
Myr

datastructures.py

This file

Path

httpcore/datastructures.py

160 lines · 4.6 KiB · Python

Last changed by

Add support for gzip, deflate, and brotli decodingTom Christiebefore adoption39b57c9

History of this file

Take it

1import typing2from urllib.parse import urlsplit34from .decoders import SUPPORTED_DECODERS, Decoder, IdentityDecoder, MultiDecoder5from .exceptions import ResponseClosed, StreamConsumed678class URL:9    def __init__(self, url: str = "") -> None:10        self.components = urlsplit(url)11        if not self.components.scheme:12            raise ValueError("No scheme included in URL.")13        if self.components.scheme not in ("http", "https"):14            raise ValueError('URL scheme must be "http" or "https".')15        if not self.components.hostname:16            raise ValueError("No hostname included in URL.")1718    @property19    def scheme(self) -> str:20        return self.components.scheme2122    @property23    def netloc(self) -> str:24        return self.components.netloc2526    @property27    def path(self) -> str:28        return self.components.path2930    @property31    def query(self) -> str:32        return self.components.query3334    @property35    def hostname(self) -> str:36        return self.components.hostname3738    @property39    def port(self) -> int:40        port = self.components.port41        if port is None:42            return {"https": 443, "http": 80}[self.scheme]43        return port4445    @property46    def target(self) -> str:47        path = self.path or "/"48        query = self.query49        if query:50            return path + "?" + query51        return path5253    @property54    def is_secure(self) -> bool:55        return self.components.scheme == "https"565758class Request:59    def __init__(60        self,61        method: str,62        url: URL,63        *,64        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),65        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",66    ):67        self.method = method68        self.url = url69        self.headers = list(headers)70        if isinstance(body, bytes):71            self.is_streaming = False72            self.body = body73        else:74            self.is_streaming = True75            self.body_aiter = body7677    async def stream(self) -> typing.AsyncIterator[bytes]:78        assert self.is_streaming7980        async for part in self.body_aiter:81            yield part828384class Response:85    def __init__(86        self,87        status_code: int,88        *,89        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),90        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",91        on_close: typing.Callable = None,92    ):93        self.status_code = status_code94        self.headers = list(headers)95        self.on_close = on_close96        self.is_closed = False97        self.is_streamed = False9899        decoders = []  # type: typing.List[Decoder]100        for header, value in self.headers:101            if header.strip().lower() == b"content-encoding":102                for part in value.split(b","):103                    part = part.strip().lower()104                    decoder_cls = SUPPORTED_DECODERS[part]105                    decoders.append(decoder_cls())106107        if len(decoders) == 0:108            self.decoder = IdentityDecoder()  # type: Decoder109        elif len(decoders) == 1:110            self.decoder = decoders[0]111        else:112            self.decoder = MultiDecoder(decoders)113114        if isinstance(body, bytes):115            self.is_closed = True116            self.body = self.decoder.decode(body) + self.decoder.flush()117        else:118            self.body_aiter = body119120    async def read(self) -> bytes:121        """122        Read and return the response content.123        """124        if not hasattr(self, "body"):125            body = b""126            async for part in self.stream():127                body += part128            self.body = body129        return self.body130131    async def stream(self) -> typing.AsyncIterator[bytes]:132        """133        A byte-iterator over the decoded response content.134        This will allow us to handle gzip, deflate, and brotli encoded responses.135        """136        if hasattr(self, "body"):137            yield self.body138        else:139            async for chunk in self.raw():140                yield self.decoder.decode(chunk)141            yield self.decoder.flush()142143    async def raw(self) -> typing.AsyncIterator[bytes]:144        """145        A byte-iterator over the raw response content.146        """147        if self.is_streamed:148            raise StreamConsumed()149        if self.is_closed:150            raise ResponseClosed()151        self.is_streamed = True152        async for part in self.body_aiter:153            yield part154        await self.close()155156    async def close(self) -> None:157        if not self.is_closed:158            self.is_closed = True159            if self.on_close is not None:160                await self.on_close()