Skip to content
Myr

models.py

This file

Path

httpcore/models.py

241 lines · 7.2 KiB · Python

Last changed by

AdaptersTom Christiebefore adoptionfab6fcd

History of this file

Take it

1import http2import typing3from urllib.parse import urlsplit45from .config import SSLConfig, TimeoutConfig6from .decoders import (7    ACCEPT_ENCODING,8    SUPPORTED_DECODERS,9    Decoder,10    IdentityDecoder,11    MultiDecoder,12)13from .exceptions import ResponseClosed, StreamConsumed141516class URL:17    def __init__(self, url: str = "") -> None:18        self.components = urlsplit(url)19        if not self.components.scheme:20            raise ValueError("No scheme included in URL.")21        if self.components.scheme not in ("http", "https"):22            raise ValueError('URL scheme must be "http" or "https".')23        if not self.components.hostname:24            raise ValueError("No hostname included in URL.")2526    @property27    def scheme(self) -> str:28        return self.components.scheme2930    @property31    def netloc(self) -> str:32        return self.components.netloc3334    @property35    def path(self) -> str:36        return self.components.path3738    @property39    def query(self) -> str:40        return self.components.query4142    @property43    def hostname(self) -> str:44        return self.components.hostname4546    @property47    def port(self) -> int:48        port = self.components.port49        if port is None:50            return {"https": 443, "http": 80}[self.scheme]51        return port5253    @property54    def full_path(self) -> str:55        path = self.path or "/"56        query = self.query57        if query:58            return path + "?" + query59        return path6061    @property62    def is_secure(self) -> bool:63        return self.components.scheme == "https"6465    @property66    def origin(self) -> "Origin":67        return Origin(self)686970class Origin:71    def __init__(self, url: typing.Union[str, URL]) -> None:72        if isinstance(url, str):73            url = URL(url)74        self.is_ssl = url.scheme == "https"75        self.hostname = url.hostname.lower()76        self.port = url.port7778    def __eq__(self, other: typing.Any) -> bool:79        return (80            isinstance(other, self.__class__)81            and self.is_ssl == other.is_ssl82            and self.hostname == other.hostname83            and self.port == other.port84        )8586    def __hash__(self) -> int:87        return hash((self.is_ssl, self.hostname, self.port))888990class Request:91    def __init__(92        self,93        method: str,94        url: typing.Union[str, URL],95        *,96        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),97        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",98    ):99        self.method = method.upper()100        self.url = URL(url) if isinstance(url, str) else url101        self.headers = list(headers)102        if isinstance(body, bytes):103            self.is_streaming = False104            self.body = body105        else:106            self.is_streaming = True107            self.body_aiter = body108        self.headers = self._auto_headers() + self.headers109110    def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:111        has_host = False112        has_content_length = False113        has_accept_encoding = False114115        for header, value in self.headers:116            header = header.strip().lower()117            if header == b"host":118                has_host = True119            elif header in (b"content-length", b"transfer-encoding"):120                has_content_length = True121            elif header == b"accept-encoding":122                has_accept_encoding = True123124        headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]125126        if not has_host:127            headers.append((b"host", self.url.netloc.encode("ascii")))128        if not has_content_length:129            if self.is_streaming:130                headers.append((b"transfer-encoding", b"chunked"))131            elif self.body:132                content_length = str(len(self.body)).encode()133                headers.append((b"content-length", content_length))134        if not has_accept_encoding:135            headers.append((b"accept-encoding", ACCEPT_ENCODING))136137        return headers138139    async def stream(self) -> typing.AsyncIterator[bytes]:140        if self.is_streaming:141            async for part in self.body_aiter:142                yield part143        elif self.body:144            yield self.body145146147class Response:148    def __init__(149        self,150        status_code: int,151        *,152        reason: typing.Optional[str] = None,153        protocol: typing.Optional[str] = None,154        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),155        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",156        on_close: typing.Callable = None,157    ):158        self.status_code = status_code159        if not reason:160            try:161                self.reason = http.HTTPStatus(status_code).phrase162            except ValueError as exc:163                self.reason = ""164        else:165            self.reason = reason166        self.protocol = protocol167        self.headers = list(headers)168        self.on_close = on_close169        self.is_closed = False170        self.is_streamed = False171172        decoders = []  # type: typing.List[Decoder]173        for header, value in self.headers:174            if header.strip().lower() == b"content-encoding":175                for part in value.split(b","):176                    part = part.strip().lower()177                    decoder_cls = SUPPORTED_DECODERS[part]178                    decoders.append(decoder_cls())179180        if len(decoders) == 0:181            self.decoder = IdentityDecoder()  # type: Decoder182        elif len(decoders) == 1:183            self.decoder = decoders[0]184        else:185            self.decoder = MultiDecoder(decoders)186187        if isinstance(body, bytes):188            self.is_closed = True189            self.body = self.decoder.decode(body) + self.decoder.flush()190        else:191            self.body_aiter = body192193    async def read(self) -> bytes:194        """195        Read and return the response content.196        """197        if not hasattr(self, "body"):198            body = b""199            async for part in self.stream():200                body += part201            self.body = body202        return self.body203204    async def stream(self) -> typing.AsyncIterator[bytes]:205        """206        A byte-iterator over the decoded response content.207        This allows us to handle gzip, deflate, and brotli encoded responses.208        """209        if hasattr(self, "body"):210            yield self.body211        else:212            async for chunk in self.raw():213                yield self.decoder.decode(chunk)214            yield self.decoder.flush()215216    async def raw(self) -> typing.AsyncIterator[bytes]:217        """218        A byte-iterator over the raw response content.219        """220        if self.is_streamed:221            raise StreamConsumed()222        if self.is_closed:223            raise ResponseClosed()224        self.is_streamed = True225        async for part in self.body_aiter:226            yield part227        await self.close()228229    async def close(self) -> None:230        """231        Close the response and release the connection.232        Automatically called if the response body is read to completion.233        """234        if not self.is_closed:235            self.is_closed = True236            if self.on_close is not None:237                await self.on_close()238239    @property240    def is_redirect(self) -> bool:241        return self.status_code in (301, 302, 303, 307, 308)