Skip to content
Myr

datastructures.py

This file

Path

httpcore/datastructures.py

283 lines · 8.4 KiB · Python

Last changed by

First pass at HTTP/2 supportTom Christiebefore adoption53f3dc4

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 full_path(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        if self.is_streaming:142            async for part in self.body_aiter:143                yield part144        elif self.body:145            yield self.body146147148class Response:149    def __init__(150        self,151        status_code: int,152        *,153        reason: typing.Optional[str] = None,154        protocol: typing.Optional[str] = None,155        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),156        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",157        on_close: typing.Callable = None,158    ):159        self.status_code = status_code160        if not reason:161            try:162                self.reason = http.HTTPStatus(status_code).phrase163            except ValueError as exc:164                self.reason = ""165        else:166            self.reason = reason167        self.protocol = protocol168        self.headers = list(headers)169        self.on_close = on_close170        self.is_closed = False171        self.is_streamed = False172173        decoders = []  # type: typing.List[Decoder]174        for header, value in self.headers:175            if header.strip().lower() == b"content-encoding":176                for part in value.split(b","):177                    part = part.strip().lower()178                    decoder_cls = SUPPORTED_DECODERS[part]179                    decoders.append(decoder_cls())180181        if len(decoders) == 0:182            self.decoder = IdentityDecoder()  # type: Decoder183        elif len(decoders) == 1:184            self.decoder = decoders[0]185        else:186            self.decoder = MultiDecoder(decoders)187188        if isinstance(body, bytes):189            self.is_closed = True190            self.body = self.decoder.decode(body) + self.decoder.flush()191        else:192            self.body_aiter = body193194    async def read(self) -> bytes:195        """196        Read and return the response content.197        """198        if not hasattr(self, "body"):199            body = b""200            async for part in self.stream():201                body += part202            self.body = body203        return self.body204205    async def stream(self) -> typing.AsyncIterator[bytes]:206        """207        A byte-iterator over the decoded response content.208        This allows us to handle gzip, deflate, and brotli encoded responses.209        """210        if hasattr(self, "body"):211            yield self.body212        else:213            async for chunk in self.raw():214                yield self.decoder.decode(chunk)215            yield self.decoder.flush()216217    async def raw(self) -> typing.AsyncIterator[bytes]:218        """219        A byte-iterator over the raw response content.220        """221        if self.is_streamed:222            raise StreamConsumed()223        if self.is_closed:224            raise ResponseClosed()225        self.is_streamed = True226        async for part in self.body_aiter:227            yield part228        await self.close()229230    async def close(self) -> None:231        """232        Close the response and release the connection.233        Automatically called if the response body is read to completion.234        """235        if not self.is_closed:236            self.is_closed = True237            if self.on_close is not None:238                await self.on_close()239240241class Client:242    async def request(243        self,244        method: str,245        url: typing.Union[str, URL],246        *,247        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),248        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",249        ssl: typing.Optional[SSLConfig] = None,250        timeout: typing.Optional[TimeoutConfig] = None,251        stream: bool = False,252    ) -> Response:253        request = Request(method, url, headers=headers, body=body)254        response = await self.send(request, ssl=ssl, timeout=timeout)255        if not stream:256            try:257                await response.read()258            finally:259                await response.close()260        return response261262    async def send(263        self,264        request: Request,265        *,266        ssl: typing.Optional[SSLConfig] = None,267        timeout: typing.Optional[TimeoutConfig] = None,268    ) -> Response:269        raise NotImplementedError()  # pragma: nocover270271    async def close(self) -> None:272        raise NotImplementedError()  # pragma: nocover273274    async def __aenter__(self) -> "Client":275        return self276277    async def __aexit__(278        self,279        exc_type: typing.Type[BaseException] = None,280        exc_value: BaseException = None,281        traceback: TracebackType = None,282    ) -> None:283        await self.close()