Skip to content
Myr

datastructures.py

This file

Path

httpcore/datastructures.py

280 lines · 8.3 KiB · Python

Last changed by

Module renamingTom Christiebefore adoptionb7d315a

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.is_ssl = url.scheme == "https"76        self.hostname = url.hostname.lower()77        self.port = url.port7879    def __eq__(self, other: typing.Any) -> bool:80        return (81            isinstance(other, self.__class__)82            and self.is_ssl == other.is_ssl83            and self.hostname == other.hostname84            and self.port == other.port85        )8687    def __hash__(self) -> int:88        return hash((self.is_ssl, self.hostname, self.port))899091class Request:92    def __init__(93        self,94        method: str,95        url: typing.Union[str, URL],96        *,97        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),98        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",99    ):100        self.method = method.upper()101        self.url = URL(url) if isinstance(url, str) else url102        self.headers = list(headers)103        if isinstance(body, bytes):104            self.is_streaming = False105            self.body = body106        else:107            self.is_streaming = True108            self.body_aiter = body109        self.headers = self._auto_headers() + self.headers110111    def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:112        has_host = False113        has_content_length = False114        has_accept_encoding = False115116        for header, value in self.headers:117            header = header.strip().lower()118            if header == b"host":119                has_host = True120            elif header in (b"content-length", b"transfer-encoding"):121                has_content_length = True122            elif header == b"accept-encoding":123                has_accept_encoding = True124125        headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]126127        if not has_host:128            headers.append((b"host", self.url.netloc.encode("ascii")))129        if not has_content_length:130            if self.is_streaming:131                headers.append((b"transfer-encoding", b"chunked"))132            elif self.body:133                content_length = str(len(self.body)).encode()134                headers.append((b"content-length", content_length))135        if not has_accept_encoding:136            headers.append((b"accept-encoding", ACCEPT_ENCODING))137138        return headers139140    async def stream(self) -> typing.AsyncIterator[bytes]:141        assert self.is_streaming142143        async for part in self.body_aiter:144            yield part145146147class Response:148    def __init__(149        self,150        status_code: int,151        *,152        reason: typing.Optional[str] = None,153        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),154        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",155        on_close: typing.Callable = None,156    ):157        self.status_code = status_code158        if not reason:159            try:160                self.reason = http.HTTPStatus(status_code).phrase161            except ValueError as exc:162                self.reason = ""163        else:164            self.reason = reason165        self.headers = list(headers)166        self.on_close = on_close167        self.is_closed = False168        self.is_streamed = False169170        decoders = []  # type: typing.List[Decoder]171        for header, value in self.headers:172            if header.strip().lower() == b"content-encoding":173                for part in value.split(b","):174                    part = part.strip().lower()175                    decoder_cls = SUPPORTED_DECODERS[part]176                    decoders.append(decoder_cls())177178        if len(decoders) == 0:179            self.decoder = IdentityDecoder()  # type: Decoder180        elif len(decoders) == 1:181            self.decoder = decoders[0]182        else:183            self.decoder = MultiDecoder(decoders)184185        if isinstance(body, bytes):186            self.is_closed = True187            self.body = self.decoder.decode(body) + self.decoder.flush()188        else:189            self.body_aiter = body190191    async def read(self) -> bytes:192        """193        Read and return the response content.194        """195        if not hasattr(self, "body"):196            body = b""197            async for part in self.stream():198                body += part199            self.body = body200        return self.body201202    async def stream(self) -> typing.AsyncIterator[bytes]:203        """204        A byte-iterator over the decoded response content.205        This allows us to handle gzip, deflate, and brotli encoded responses.206        """207        if hasattr(self, "body"):208            yield self.body209        else:210            async for chunk in self.raw():211                yield self.decoder.decode(chunk)212            yield self.decoder.flush()213214    async def raw(self) -> typing.AsyncIterator[bytes]:215        """216        A byte-iterator over the raw response content.217        """218        if self.is_streamed:219            raise StreamConsumed()220        if self.is_closed:221            raise ResponseClosed()222        self.is_streamed = True223        async for part in self.body_aiter:224            yield part225        await self.close()226227    async def close(self) -> None:228        """229        Close the response and release the connection.230        Automatically called if the response body is read to completion.231        """232        if not self.is_closed:233            self.is_closed = True234            if self.on_close is not None:235                await self.on_close()236237238class Client:239    async def request(240        self,241        method: str,242        url: typing.Union[str, URL],243        *,244        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),245        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",246        ssl: typing.Optional[SSLConfig] = None,247        timeout: typing.Optional[TimeoutConfig] = None,248        stream: bool = False,249    ) -> Response:250        request = Request(method, url, headers=headers, body=body)251        response = await self.send(request, ssl=ssl, timeout=timeout)252        if not stream:253            try:254                await response.read()255            finally:256                await response.close()257        return response258259    async def send(260        self,261        request: Request,262        *,263        ssl: typing.Optional[SSLConfig] = None,264        timeout: typing.Optional[TimeoutConfig] = None,265    ) -> Response:266        raise NotImplementedError()  # pragma: nocover267268    async def close(self) -> None:269        raise NotImplementedError()  # pragma: nocover270271    async def __aenter__(self) -> "Client":272        return self273274    async def __aexit__(275        self,276        exc_type: typing.Type[BaseException] = None,277        exc_value: BaseException = None,278        traceback: TracebackType = None,279    ) -> None:280        await self.close()