Skip to content
Myr

models.py

This file

Path

httpcore/models.py

565 lines · 17.2 KiB · Python

Last changed by

Add response.text and response.encodingTom Christiebefore adoptiond8df61b

History of this file

Take it

1import cgi2import typing3from urllib.parse import urlsplit45import chardet67from .config import SSLConfig, TimeoutConfig8from .decoders import (9    ACCEPT_ENCODING,10    SUPPORTED_DECODERS,11    Decoder,12    IdentityDecoder,13    MultiDecoder,14)15from .exceptions import ResponseClosed, ResponseNotRead, StreamConsumed16from .status_codes import codes17from .utils import (18    get_reason_phrase,19    is_known_encoding,20    normalize_header_key,21    normalize_header_value,22)2324URLTypes = typing.Union["URL", str]2526HeaderTypes = typing.Union[27    "Headers",28    typing.Dict[typing.AnyStr, typing.AnyStr],29    typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],30]3132ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]333435class URL:36    def __init__(self, url: URLTypes) -> None:37        if isinstance(url, str):38            self.components = urlsplit(url)39        else:40            self.components = url.components4142        if not self.components.scheme:43            raise ValueError("No scheme included in URL.")44        if self.components.scheme not in ("http", "https"):45            raise ValueError('URL scheme must be "http" or "https".')46        if not self.components.hostname:47            raise ValueError("No hostname included in URL.")4849    @property50    def scheme(self) -> str:51        return self.components.scheme5253    @property54    def netloc(self) -> str:55        return self.components.netloc5657    @property58    def path(self) -> str:59        return self.components.path6061    @property62    def query(self) -> str:63        return self.components.query6465    @property66    def fragment(self) -> str:67        return self.components.fragment6869    @property70    def hostname(self) -> str:71        return self.components.hostname7273    @property74    def port(self) -> int:75        port = self.components.port76        if port is None:77            return {"https": 443, "http": 80}[self.scheme]78        return port7980    @property81    def full_path(self) -> str:82        path = self.path or "/"83        query = self.query84        if query:85            return path + "?" + query86        return path8788    @property89    def is_secure(self) -> bool:90        return self.components.scheme == "https"9192    @property93    def origin(self) -> "Origin":94        return Origin(self)9596    def __hash__(self) -> int:97        return hash(str(self))9899    def __eq__(self, other: typing.Any) -> bool:100        return isinstance(other, URL) and str(self) == str(other)101102    def __str__(self) -> str:103        return self.components.geturl()104105    def __repr__(self) -> str:106        class_name = self.__class__.__name__107        url_str = str(self)108        return f"{class_name}({url_str!r})"109110111class Origin:112    def __init__(self, url: typing.Union[str, URL]) -> None:113        if isinstance(url, str):114            url = URL(url)115        self.is_ssl = url.scheme == "https"116        self.hostname = url.hostname.lower()117        self.port = url.port118119    def __eq__(self, other: typing.Any) -> bool:120        return (121            isinstance(other, self.__class__)122            and self.is_ssl == other.is_ssl123            and self.hostname == other.hostname124            and self.port == other.port125        )126127    def __hash__(self) -> int:128        return hash((self.is_ssl, self.hostname, self.port))129130131class Headers(typing.MutableMapping[str, str]):132    """133    A case-insensitive multidict.134    """135136    def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:137        if headers is None:138            self._list = []  # type: typing.List[typing.Tuple[bytes, bytes]]139        elif isinstance(headers, Headers):140            self._list = list(headers.raw)141        elif isinstance(headers, dict):142            self._list = [143                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))144                for k, v in headers.items()145            ]146        else:147            self._list = [148                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))149                for k, v in headers150            ]151        self._encoding = encoding152153    @property154    def encoding(self) -> str:155        """156        Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be157        seen in the wild.158        """159        if self._encoding is None:160            for encoding in ["ascii", "utf-8"]:161                for key, value in self.raw:162                    try:163                        key.decode(encoding)164                        value.decode(encoding)165                    except UnicodeDecodeError:166                        break167                else:168                    # The else block runs if 'break' did not occur, meaning169                    # all values fitted the encoding.170                    self._encoding = encoding171                    break172            else:173                # The ISO-8859-1 encoding covers all 256 code points in a byte,174                # so will never raise decode errors.175                self._encoding = "iso-8859-1"176        return self._encoding177178    @encoding.setter179    def encoding(self, value: str) -> None:180        self._encoding = value181182    @property183    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:184        """185        Returns a list of the raw header items, as byte pairs.186        May be mutated in-place.187        """188        return self._list189190    def keys(self) -> typing.List[str]:  # type: ignore191        return [key.decode(self.encoding) for key, value in self._list]192193    def values(self) -> typing.List[str]:  # type: ignore194        return [value.decode(self.encoding) for key, value in self._list]195196    def items(self) -> typing.List[typing.Tuple[str, str]]:  # type: ignore197        return [198            (key.decode(self.encoding), value.decode(self.encoding))199            for key, value in self._list200        ]201202    def get(self, key: str, default: typing.Any = None) -> typing.Any:203        try:204            return self[key]205        except KeyError:206            return default207208    def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:209        """210        Return multiple header values.211        """212        get_header_key = key.lower().encode(self.encoding)213214        values = [215            item_value.decode(self.encoding)216            for item_key, item_value in self._list217            if item_key == get_header_key218        ]219220        if not split_commas:221            return values222223        split_values = []224        for value in values:225            split_values.extend([item.strip() for item in value.split(",")])226        return split_values227228    def __getitem__(self, key: str) -> str:229        """230        Return a single header value.231232        If there are multiple headers with the same key, then we concatenate233        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2234        """235        normalized_key = key.lower().encode(self.encoding)236237        items = []238        for header_key, header_value in self._list:239            if header_key == normalized_key:240                items.append(header_value.decode(self.encoding))241242        if items:243            return ", ".join(items)244245        raise KeyError(key)246247    def __setitem__(self, key: str, value: str) -> None:248        """249        Set the header `key` to `value`, removing any duplicate entries.250        Retains insertion order.251        """252        set_key = key.lower().encode(self.encoding)253        set_value = value.encode(self.encoding)254255        found_indexes = []256        for idx, (item_key, item_value) in enumerate(self._list):257            if item_key == set_key:258                found_indexes.append(idx)259260        for idx in reversed(found_indexes[1:]):261            del self._list[idx]262263        if found_indexes:264            idx = found_indexes[0]265            self._list[idx] = (set_key, set_value)266        else:267            self._list.append((set_key, set_value))268269    def __delitem__(self, key: str) -> None:270        """271        Remove the header `key`.272        """273        del_key = key.lower().encode(self.encoding)274275        pop_indexes = []276        for idx, (item_key, item_value) in enumerate(self._list):277            if item_key == del_key:278                pop_indexes.append(idx)279280        for idx in reversed(pop_indexes):281            del self._list[idx]282283    def __contains__(self, key: typing.Any) -> bool:284        get_header_key = key.lower().encode(self.encoding)285        for header_key, header_value in self._list:286            if header_key == get_header_key:287                return True288        return False289290    def __iter__(self) -> typing.Iterator[typing.Any]:291        return iter(self.keys())292293    def __len__(self) -> int:294        return len(self._list)295296    def __eq__(self, other: typing.Any) -> bool:297        if not isinstance(other, Headers):298            return False299        return sorted(self._list) == sorted(other._list)300301    def __repr__(self) -> str:302        class_name = self.__class__.__name__303304        encoding_str = ""305        if self.encoding != "ascii":306            encoding_str = f", encoding={self.encoding!r}"307308        as_dict = dict(self.items())309        if len(as_dict) == len(self):310            return f"{class_name}({as_dict!r}{encoding_str})"311        as_list = self.items()312        return f"{class_name}({as_list!r}{encoding_str})"313314315class Request:316    def __init__(317        self,318        method: str,319        url: typing.Union[str, URL],320        *,321        headers: HeaderTypes = None,322        content: ByteOrByteStream = b"",323    ):324        self.method = method.upper()325        self.url = URL(url) if isinstance(url, str) else url326        if isinstance(content, bytes):327            self.is_streaming = False328            self.content = content329        else:330            self.is_streaming = True331            self.content_aiter = content332        self.headers = Headers(headers)333334    async def read(self) -> bytes:335        """336        Read and return the response content.337        """338        if not hasattr(self, "content"):339            content = b""340            async for part in self.stream():341                content += part342            self.content = content343        return self.content344345    async def stream(self) -> typing.AsyncIterator[bytes]:346        if self.is_streaming:347            async for part in self.content_aiter:348                yield part349        elif self.content:350            yield self.content351352    def prepare(self) -> None:353        """354        Adds in any default headers. When using the `Client`, this will355        end up being called into by the `prepare_request()` stage.356357        You can omit this behavior by calling `Client.send()` with an358        explicitly built `Request` instance.359        """360        auto_headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]361362        has_host = "host" in self.headers363        has_content_length = (364            "content-length" in self.headers or "transfer-encoding" in self.headers365        )366        has_accept_encoding = "accept-encoding" in self.headers367368        if not has_host:369            auto_headers.append((b"host", self.url.netloc.encode("ascii")))370        if not has_content_length:371            if self.is_streaming:372                auto_headers.append((b"transfer-encoding", b"chunked"))373            elif self.content:374                content_length = str(len(self.content)).encode()375                auto_headers.append((b"content-length", content_length))376        if not has_accept_encoding:377            auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))378379        for item in reversed(auto_headers):380            self.headers.raw.insert(0, item)381382383class Response:384    def __init__(385        self,386        status_code: int,387        *,388        reason_phrase: str = None,389        protocol: str = None,390        headers: HeaderTypes = None,391        content: ByteOrByteStream = b"",392        on_close: typing.Callable = None,393        request: Request = None,394        history: typing.List["Response"] = None,395    ):396        self.status_code = status_code397        self.reason_phrase = reason_phrase or get_reason_phrase(status_code)398        self.protocol = protocol399        self.headers = Headers(headers)400401        if isinstance(content, bytes):402            self.is_closed = True403            self.is_stream_consumed = True404            self._raw_content = content405        else:406            self.is_closed = False407            self.is_stream_consumed = False408            self._raw_stream = content409410        self.on_close = on_close411        self.request = request412        self.history = [] if history is None else list(history)413        self.next = None  # typing.Optional[typing.Callable]414415    @property416    def url(self) -> typing.Optional[URL]:417        """418        Returns the URL for which the request was made.419420        Requires that `request` was provided when instantiating the response.421        """422        return None if self.request is None else self.request.url423424    @property425    def content(self) -> bytes:426        if not hasattr(self, "_content"):427            if hasattr(self, "_raw_content"):428                content = self.decoder.decode(self._raw_content)429                content += self.decoder.flush()430                self._content = content431            else:432                raise ResponseNotRead()433        return self._content434435    @property436    def text(self) -> str:437        if not hasattr(self, "_text"):438            content = self.content439            if not content:440                self._text = ""441            else:442                encoding = self.encoding443                self._text = content.decode(encoding, errors="replace")444        return self._text445446    @property447    def encoding(self) -> str:448        if not hasattr(self, "_encoding"):449            encoding = self.charset_encoding450            if encoding is None or not is_known_encoding(encoding):451                encoding = self.apparent_encoding452                if encoding is None or not is_known_encoding(encoding):453                    encoding = "utf-8"454            self._encoding = encoding455        return self._encoding456457    @encoding.setter458    def encoding(self, value: str) -> None:459        self._encoding = value460461    @property462    def charset_encoding(self) -> typing.Optional[str]:463        """464        Return the encoding, as specified by the Content-Type header.465        """466        content_type = self.headers.get("Content-Type")467        if content_type is None:468            return None469470        parsed = cgi.parse_header(content_type)[-1]471        return parsed.get("charset")472473    @property474    def apparent_encoding(self) -> typing.Optional[str]:475        """476        Return the encoding, as it appears to autodetection.477        """478        return chardet.detect(self.content)["encoding"]479480    @property481    def decoder(self) -> Decoder:482        """483        Returns a decoder instance which can be used to decode the raw byte484        content, depending on the Content-Encoding used in the response.485        """486        if not hasattr(self, "_decoder"):487            decoders = []  # type: typing.List[Decoder]488            values = self.headers.getlist("content-encoding", split_commas=True)489            for value in values:490                value = value.strip().lower()491                decoder_cls = SUPPORTED_DECODERS[value]492                decoders.append(decoder_cls())493494            if len(decoders) == 1:495                self._decoder = decoders[0]496            elif len(decoders) > 1:497                self._decoder = MultiDecoder(decoders)498            else:499                self._decoder = IdentityDecoder()500501        return self._decoder502503    async def read(self) -> bytes:504        """505        Read and return the response content.506        """507        if not hasattr(self, "_content"):508            content = b""509            async for part in self.stream():510                content += part511            self._content = content512        return self._content513514    async def stream(self) -> typing.AsyncIterator[bytes]:515        """516        A byte-iterator over the decoded response content.517        This allows us to handle gzip, deflate, and brotli encoded responses.518        """519        if hasattr(self, "_content"):520            yield self._content521        else:522            async for chunk in self.raw():523                yield self.decoder.decode(chunk)524            yield self.decoder.flush()525526    async def raw(self) -> typing.AsyncIterator[bytes]:527        """528        A byte-iterator over the raw response content.529        """530        if hasattr(self, "_raw_content"):531            yield self._raw_content532        else:533            if self.is_stream_consumed:534                raise StreamConsumed()535            if self.is_closed:536                raise ResponseClosed()537538            self.is_stream_consumed = True539            async for part in self._raw_stream:540                yield part541            await self.close()542543    async def close(self) -> None:544        """545        Close the response and release the connection.546        Automatically called if the response body is read to completion.547        """548        if not self.is_closed:549            self.is_closed = True550            if self.on_close is not None:551                await self.on_close()552553    @property554    def is_redirect(self) -> bool:555        return (556            self.status_code557            in (558                codes.moved_permanently,559                codes.found,560                codes.see_other,561                codes.temporary_redirect,562                codes.permanent_redirect,563            )564            and "location" in self.headers565        )