Skip to content
Myr

datastructures.py

This file

Path

httpcore/datastructures.py

209 lines · 6.2 KiB · Python

Last changed by

Add response.reasonTom Christiebefore adoptionfc7cf9d

History of this file

Take it

1import http2import typing3from urllib.parse import urlsplit45from .decoders import (6    ACCEPT_ENCODING,7    SUPPORTED_DECODERS,8    Decoder,9    IdentityDecoder,10    MultiDecoder,11)12from .exceptions import ResponseClosed, StreamConsumed131415class URL:16    def __init__(self, url: str = "") -> None:17        self.components = urlsplit(url)18        if not self.components.scheme:19            raise ValueError("No scheme included in URL.")20        if self.components.scheme not in ("http", "https"):21            raise ValueError('URL scheme must be "http" or "https".')22        if not self.components.hostname:23            raise ValueError("No hostname included in URL.")2425    @property26    def scheme(self) -> str:27        return self.components.scheme2829    @property30    def netloc(self) -> str:31        return self.components.netloc3233    @property34    def path(self) -> str:35        return self.components.path3637    @property38    def query(self) -> str:39        return self.components.query4041    @property42    def hostname(self) -> str:43        return self.components.hostname4445    @property46    def port(self) -> int:47        port = self.components.port48        if port is None:49            return {"https": 443, "http": 80}[self.scheme]50        return port5152    @property53    def target(self) -> str:54        path = self.path or "/"55        query = self.query56        if query:57            return path + "?" + query58        return path5960    @property61    def is_secure(self) -> bool:62        return self.components.scheme == "https"636465class Request:66    def __init__(67        self,68        method: str,69        url: typing.Union[str, URL],70        *,71        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),72        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",73    ):74        self.method = method75        self.url = URL(url) if isinstance(url, str) else url76        self.headers = list(headers)77        if isinstance(body, bytes):78            self.is_streaming = False79            self.body = body80        else:81            self.is_streaming = True82            self.body_aiter = body83        self.headers = self._auto_headers() + self.headers8485    def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:86        has_host = False87        has_content_length = False88        has_accept_encoding = False8990        for header, value in self.headers:91            header = header.strip().lower()92            if header == b"host":93                has_host = True94            elif header in (b"content-length", b"transfer-encoding"):95                has_content_length = True96            elif header == b"accept-encoding":97                has_accept_encoding = True9899        headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]100101        if not has_host:102            headers.append((b"host", self.url.netloc.encode("ascii")))103        if not has_content_length:104            if self.is_streaming:105                headers.append((b"transfer-encoding", b"chunked"))106            elif self.body:107                content_length = str(len(self.body)).encode()108                headers.append((b"content-length", content_length))109        if not has_accept_encoding:110            headers.append((b"accept-encoding", ACCEPT_ENCODING))111112        return headers113114    async def stream(self) -> typing.AsyncIterator[bytes]:115        assert self.is_streaming116117        async for part in self.body_aiter:118            yield part119120121class Response:122    def __init__(123        self,124        status_code: int,125        *,126        reason: typing.Optional[str] = None,127        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),128        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",129        on_close: typing.Callable = None,130    ):131        self.status_code = status_code132        if not reason:133            try:134                self.reason = http.HTTPStatus(status_code).phrase135            except ValueError as exc:136                self.reason = ""137        else:138            self.reason = reason139        self.headers = list(headers)140        self.on_close = on_close141        self.is_closed = False142        self.is_streamed = False143144        decoders = []  # type: typing.List[Decoder]145        for header, value in self.headers:146            if header.strip().lower() == b"content-encoding":147                for part in value.split(b","):148                    part = part.strip().lower()149                    decoder_cls = SUPPORTED_DECODERS[part]150                    decoders.append(decoder_cls())151152        if len(decoders) == 0:153            self.decoder = IdentityDecoder()  # type: Decoder154        elif len(decoders) == 1:155            self.decoder = decoders[0]156        else:157            self.decoder = MultiDecoder(decoders)158159        if isinstance(body, bytes):160            self.is_closed = True161            self.body = self.decoder.decode(body) + self.decoder.flush()162        else:163            self.body_aiter = body164165    async def read(self) -> bytes:166        """167        Read and return the response content.168        """169        if not hasattr(self, "body"):170            body = b""171            async for part in self.stream():172                body += part173            self.body = body174        return self.body175176    async def stream(self) -> typing.AsyncIterator[bytes]:177        """178        A byte-iterator over the decoded response content.179        This allows us to handle gzip, deflate, and brotli encoded responses.180        """181        if hasattr(self, "body"):182            yield self.body183        else:184            async for chunk in self.raw():185                yield self.decoder.decode(chunk)186            yield self.decoder.flush()187188    async def raw(self) -> typing.AsyncIterator[bytes]:189        """190        A byte-iterator over the raw response content.191        """192        if self.is_streamed:193            raise StreamConsumed()194        if self.is_closed:195            raise ResponseClosed()196        self.is_streamed = True197        async for part in self.body_aiter:198            yield part199        await self.close()200201    async def close(self) -> None:202        """203        Close the response and release the connection.204        Automatically called if the response body is read to completion.205        """206        if not self.is_closed:207            self.is_closed = True208            if self.on_close is not None:209                await self.on_close()