Skip to content
Myr

models.py

This file

Path

httpcore/models.py

352 lines · 10.6 KiB · Python

Last changed by

Rollin'Tom Christiebefore adoption8a29a0a

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 fragment(self) -> str:44        return self.components.fragment4546    @property47    def hostname(self) -> str:48        return self.components.hostname4950    @property51    def port(self) -> int:52        port = self.components.port53        if port is None:54            return {"https": 443, "http": 80}[self.scheme]55        return port5657    @property58    def full_path(self) -> str:59        path = self.path or "/"60        query = self.query61        if query:62            return path + "?" + query63        return path6465    @property66    def is_secure(self) -> bool:67        return self.components.scheme == "https"6869    @property70    def origin(self) -> "Origin":71        return Origin(self)727374class Origin:75    def __init__(self, url: typing.Union[str, URL]) -> None:76        if isinstance(url, str):77            url = URL(url)78        self.is_ssl = url.scheme == "https"79        self.hostname = url.hostname.lower()80        self.port = url.port8182    def __eq__(self, other: typing.Any) -> bool:83        return (84            isinstance(other, self.__class__)85            and self.is_ssl == other.is_ssl86            and self.hostname == other.hostname87            and self.port == other.port88        )8990    def __hash__(self) -> int:91        return hash((self.is_ssl, self.hostname, self.port))929394class Headers(typing.MutableMapping[str, str]):95    """96    A case-insensitive multidict.97    """9899    def __init__(self, headers: typing.List[typing.Tuple[bytes, bytes]]) -> None:100        self._list = [(k.lower(), v) for k, v in headers]101102    @property103    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:104        return self._list105106    def keys(self) -> typing.List[str]:  # type: ignore107        return [key.decode("latin-1") for key, value in self._list]108109    def values(self) -> typing.List[str]:  # type: ignore110        return [value.decode("latin-1") for key, value in self._list]111112    def items(self) -> typing.List[typing.Tuple[str, str]]:  # type: ignore113        return [114            (key.decode("latin-1"), value.decode("latin-1"))115            for key, value in self._list116        ]117118    def get(self, key: str, default: typing.Any = None) -> typing.Any:119        try:120            return self[key]121        except KeyError:122            return default123124    def getlist(self, key: str) -> typing.List[str]:125        get_header_key = key.lower().encode("latin-1")126        return [127            item_value.decode("latin-1")128            for item_key, item_value in self._list129            if item_key == get_header_key130        ]131132    def __getitem__(self, key: str) -> str:133        get_header_key = key.lower().encode("latin-1")134        for header_key, header_value in self._list:135            if header_key == get_header_key:136                return header_value.decode("latin-1")137        raise KeyError(key)138139    def __setitem__(self, key: str, value: str) -> None:140        """141        Set the header `key` to `value`, removing any duplicate entries.142        Retains insertion order.143        """144        set_key = key.lower().encode("latin-1")145        set_value = value.encode("latin-1")146147        found_indexes = []148        for idx, (item_key, item_value) in enumerate(self._list):149            if item_key == set_key:150                found_indexes.append(idx)151152        for idx in reversed(found_indexes[1:]):153            del self._list[idx]154155        if found_indexes:156            idx = found_indexes[0]157            self._list[idx] = (set_key, set_value)158        else:159            self._list.append((set_key, set_value))160161    def __delitem__(self, key: str) -> None:162        """163        Remove the header `key`.164        """165        del_key = key.lower().encode("latin-1")166167        pop_indexes = []168        for idx, (item_key, item_value) in enumerate(self._list):169            if item_key == del_key:170                pop_indexes.append(idx)171172        for idx in reversed(pop_indexes):173            del self._list[idx]174175    def __contains__(self, key: typing.Any) -> bool:176        get_header_key = key.lower().encode("latin-1")177        for header_key, header_value in self._list:178            if header_key == get_header_key:179                return True180        return False181182    def __iter__(self) -> typing.Iterator[typing.Any]:183        return iter(self.keys())184185    def __len__(self) -> int:186        return len(self._list)187188    def __eq__(self, other: typing.Any) -> bool:189        if not isinstance(other, Headers):190            return False191        return sorted(self._list) == sorted(other._list)192193    def __repr__(self) -> str:194        class_name = self.__class__.__name__195        as_dict = dict(self.items())196        if len(as_dict) == len(self):197            return f"{class_name}({as_dict!r})"198        return f"{class_name}(raw={self.raw!r})"199200201class Request:202    def __init__(203        self,204        method: str,205        url: typing.Union[str, URL],206        *,207        headers: typing.List[typing.Tuple[bytes, bytes]] = [],208        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",209    ):210        self.method = method.upper()211        self.url = URL(url) if isinstance(url, str) else url212        if isinstance(body, bytes):213            self.is_streaming = False214            self.body = body215        else:216            self.is_streaming = True217            self.body_aiter = body218        self.headers = self.build_headers(headers)219220    def build_headers(221        self, init_headers: typing.List[typing.Tuple[bytes, bytes]]222    ) -> Headers:223        has_host = False224        has_content_length = False225        has_accept_encoding = False226227        for header, value in init_headers:228            header = header.strip().lower()229            if header == b"host":230                has_host = True231            elif header in (b"content-length", b"transfer-encoding"):232                has_content_length = True233            elif header == b"accept-encoding":234                has_accept_encoding = True235236        auto_headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]237238        if not has_host:239            auto_headers.append((b"host", self.url.netloc.encode("ascii")))240        if not has_content_length:241            if self.is_streaming:242                auto_headers.append((b"transfer-encoding", b"chunked"))243            elif self.body:244                content_length = str(len(self.body)).encode()245                auto_headers.append((b"content-length", content_length))246        if not has_accept_encoding:247            auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))248249        return Headers(auto_headers + init_headers)250251    async def stream(self) -> typing.AsyncIterator[bytes]:252        if self.is_streaming:253            async for part in self.body_aiter:254                yield part255        elif self.body:256            yield self.body257258259class Response:260    def __init__(261        self,262        status_code: int,263        *,264        reason: typing.Optional[str] = None,265        protocol: typing.Optional[str] = None,266        headers: typing.List[typing.Tuple[bytes, bytes]] = [],267        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",268        on_close: typing.Callable = None,269    ):270        self.status_code = status_code271        if not reason:272            try:273                self.reason = http.HTTPStatus(status_code).phrase274            except ValueError as exc:275                self.reason = ""276        else:277            self.reason = reason278        self.protocol = protocol279        self.headers = Headers(headers)280        self.on_close = on_close281        self.is_closed = False282        self.is_streamed = False283284        decoders = []  # type: typing.List[Decoder]285        value = self.headers.get("content-encoding", "identity")286        for part in value.split(","):287            part = part.strip().lower()288            decoder_cls = SUPPORTED_DECODERS[part]289            decoders.append(decoder_cls())290291        if len(decoders) == 0:292            self.decoder = IdentityDecoder()  # type: Decoder293        elif len(decoders) == 1:294            self.decoder = decoders[0]295        else:296            self.decoder = MultiDecoder(decoders)297298        if isinstance(body, bytes):299            self.is_closed = True300            self.body = self.decoder.decode(body) + self.decoder.flush()301        else:302            self.body_aiter = body303304    async def read(self) -> bytes:305        """306        Read and return the response content.307        """308        if not hasattr(self, "body"):309            body = b""310            async for part in self.stream():311                body += part312            self.body = body313        return self.body314315    async def stream(self) -> typing.AsyncIterator[bytes]:316        """317        A byte-iterator over the decoded response content.318        This allows us to handle gzip, deflate, and brotli encoded responses.319        """320        if hasattr(self, "body"):321            yield self.body322        else:323            async for chunk in self.raw():324                yield self.decoder.decode(chunk)325            yield self.decoder.flush()326327    async def raw(self) -> typing.AsyncIterator[bytes]:328        """329        A byte-iterator over the raw response content.330        """331        if self.is_streamed:332            raise StreamConsumed()333        if self.is_closed:334            raise ResponseClosed()335        self.is_streamed = True336        async for part in self.body_aiter:337            yield part338        await self.close()339340    async def close(self) -> None:341        """342        Close the response and release the connection.343        Automatically called if the response body is read to completion.344        """345        if not self.is_closed:346            self.is_closed = True347            if self.on_close is not None:348                await self.on_close()349350    @property351    def is_redirect(self) -> bool:352        return self.status_code in (301, 302, 303, 307, 308)