Skip to content
Myr

_models.py

This file

Path

httpx/_models.py

1,472 lines · 49.9 KiB · Python

Last changed by

Add `response.next_request` (#1334)Tom Christiebefore adoption3f51392

History of this file

Take it

1import cgi2import contextlib3import datetime4import email.message5import json as jsonlib6import typing7import urllib.request8from collections.abc import MutableMapping9from http.cookiejar import Cookie, CookieJar10from urllib.parse import parse_qsl, quote, unquote, urlencode1112import rfc398613import rfc3986.exceptions1415from ._content import PlainByteStream, encode_request, encode_response16from ._decoders import (17    SUPPORTED_DECODERS,18    ContentDecoder,19    IdentityDecoder,20    LineDecoder,21    MultiDecoder,22    TextDecoder,23)24from ._exceptions import (25    HTTPCORE_EXC_MAP,26    CookieConflict,27    DecodingError,28    HTTPStatusError,29    InvalidURL,30    NotRedirectResponse,31    RequestNotRead,32    ResponseClosed,33    ResponseNotRead,34    StreamConsumed,35    map_exceptions,36)37from ._status_codes import codes38from ._types import (39    ByteStream,40    CookieTypes,41    HeaderTypes,42    PrimitiveData,43    QueryParamTypes,44    RawURL,45    RequestContent,46    RequestData,47    RequestFiles,48    ResponseContent,49    URLTypes,50)51from ._utils import (52    flatten_queryparams,53    guess_json_utf,54    is_known_encoding,55    normalize_header_key,56    normalize_header_value,57    obfuscate_sensitive_headers,58    parse_header_links,59    str_query_param,60)616263class URL:64    """65    url = httpx.URL("HTTPS://jo%40email.com:a%20secret@example.com:1234/pa%20th?search=ab#anchorlink")6667    assert url.scheme == "https"68    assert url.username == "jo@email.com"69    assert url.password == "a secret"70    assert url.userinfo == b"jo%40email.com:a%20secret"71    assert url.host == "example.com"72    assert url.port == 123473    assert url.netloc == "example.com:1234"74    assert url.path == "/pa th"75    assert url.query == b"?search=ab"76    assert url.raw_path == b"/pa%20th?search=ab"77    assert url.fragment == "anchorlink"7879    The components of a URL are broken down like this:8081    https://jo%40email.com:a%20secret@example.com:1234/pa%20th?search=ab#anchorlink82    [scheme][  username  ] [password] [  host  ][port][ path ] [ query ] [fragment]83            [       userinfo        ] [    netloc    ][    raw_path    ]8485    Note that:8687    * `url.scheme` is normalized to always be lowercased.8889    * `url.host` is normalized to always be lowercased, and is IDNA encoded. For instance:90       url = httpx.URL("http://中国.icom.museum")91       assert url.host == "xn--fiqs8s.icom.museum"9293    * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work with94      `url.username` and `url.password` instead, which handle the URL escaping.9596    * `url.raw_path` is raw bytes of both the path and query, without URL escaping.97      This portion is used as the target when constructing HTTP requests. Usually you'll98      want to work with `url.path` instead.99100    * `url.query` is raw bytes, without URL escaping. A URL query string portion can only101      be properly URL escaped when decoding the parameter names and values themselves.102    """103104    def __init__(105        self, url: typing.Union["URL", str, RawURL] = "", params: QueryParamTypes = None106    ) -> None:107        if isinstance(url, (str, tuple)):108            if isinstance(url, tuple):109                raw_scheme, raw_host, port, raw_path = url110                scheme = raw_scheme.decode("ascii")111                host = raw_host.decode("ascii")112                port_str = "" if port is None else f":{port}"113                path = raw_path.decode("ascii")114                url = f"{scheme}://{host}{port_str}{path}"115116            try:117                self._uri_reference = rfc3986.iri_reference(url).encode()118            except rfc3986.exceptions.InvalidAuthority as exc:119                raise InvalidURL(message=str(exc)) from None120121            if self.is_absolute_url:122                # We don't want to normalize relative URLs, since doing so123                # removes any leading `../` portion.124                self._uri_reference = self._uri_reference.normalize()125        elif isinstance(url, URL):126            self._uri_reference = url._uri_reference127        else:128            raise TypeError(129                f"Invalid type for url.  Expected str or httpx.URL, got {type(url)}"130            )131132        # Add any query parameters, merging with any in the URL if needed.133        if params:134            if self._uri_reference.query:135                url_params = QueryParams(self._uri_reference.query)136                url_params.update(params)137                query_string = str(url_params)138            else:139                query_string = str(QueryParams(params))140            self._uri_reference = self._uri_reference.copy_with(query=query_string)141142    @property143    def scheme(self) -> str:144        """145        The URL scheme, such as "http", "https".146        Always normalised to lowercase.147        """148        return self._uri_reference.scheme or ""149150    @property151    def userinfo(self) -> bytes:152        """153        The URL userinfo as a raw bytestring.154        For example: b"jo%40email.com:a%20secret".155        """156        userinfo = self._uri_reference.userinfo or ""157        return userinfo.encode("ascii")158159    @property160    def username(self) -> str:161        """162        The URL username as a string, with URL decoding applied.163        For example: "jo@email.com"164        """165        userinfo = self._uri_reference.userinfo or ""166        return unquote(userinfo.partition(":")[0])167168    @property169    def password(self) -> str:170        """171        The URL password as a string, with URL decoding applied.172        For example: "a secret"173        """174        userinfo = self._uri_reference.userinfo or ""175        return unquote(userinfo.partition(":")[2])176177    @property178    def host(self) -> str:179        """180        The URL host as a string.181        Always normlized to lowercase, and IDNA encoded.182183        Examples:184185        url = httpx.URL("http://www.EXAMPLE.org")186        assert url.host == "www.example.org"187188        url = httpx.URL("http://中国.icom.museum")189        assert url.host == "xn--fiqs8s.icom.museum"190        """191        return self._uri_reference.host or ""192193    @property194    def port(self) -> typing.Optional[int]:195        """196        The URL port as an integer.197        """198        port = self._uri_reference.port199        return int(port) if port else None200201    @property202    def netloc(self) -> str:203        """204        Either `<host>` or `<host>:<port>` as a string.205        Always normlized to lowercase, and IDNA encoded.206        """207        host = self._uri_reference.host or ""208        port = self._uri_reference.port209        return host if port is None else f"{host}:{port}"210211    @property212    def path(self) -> str:213        """214        The URL path as a string. Excluding the query string, and URL decoded.215216        For example:217218        url = httpx.URL("https://example.com/pa%20th")219        assert url.path == "/pa th"220        """221        path = self._uri_reference.path or "/"222        return unquote(path)223224    @property225    def query(self) -> bytes:226        """227        The URL query string, as raw bytes, excluding the leading b"?".228        Note that URL decoding can only be applied on URL query strings229        at the point of decoding the individual parameter names/values.230        """231        query = self._uri_reference.query or ""232        return query.encode("ascii")233234    @property235    def raw_path(self) -> bytes:236        """237        The complete URL path and query string as raw bytes.238        Used as the target when constructing HTTP requests.239240        For example:241242        GET /users?search=some%20text HTTP/1.1243        Host: www.example.org244        Connection: close245        """246        path = self._uri_reference.path or "/"247        if self._uri_reference.query is not None:248            path += "?" + self._uri_reference.query249        return path.encode("ascii")250251    @property252    def fragment(self) -> str:253        """254        The URL fragments, as used in HTML anchors.255        As a string, without the leading '#'.256        """257        return self._uri_reference.fragment or ""258259    @property260    def raw(self) -> RawURL:261        """262        The URL in the raw representation used by the low level263        transport API. For example, see `httpcore`.264265        Provides the (scheme, host, port, target) for the outgoing request.266        """267        return (268            self.scheme.encode("ascii"),269            self.host.encode("ascii"),270            self.port,271            self.raw_path,272        )273274    @property275    def is_absolute_url(self) -> bool:276        """277        Return `True` for absolute URLs such as 'http://example.com/path',278        and `False` for relative URLs such as '/path'.279        """280        # We don't use `.is_absolute` from `rfc3986` because it treats281        # URLs with a fragment portion as not absolute.282        # What we actually care about is if the URL provides283        # a scheme and hostname to which connections should be made.284        return bool(self.scheme and self.host)285286    @property287    def is_relative_url(self) -> bool:288        """289        Return `False` for absolute URLs such as 'http://example.com/path',290        and `True` for relative URLs such as '/path'.291        """292        return not self.is_absolute_url293294    def copy_with(self, **kwargs: typing.Any) -> "URL":295        """296        Copy this URL, returning a new URL with some components altered.297        Accepts the same set of parameters as the components that are made298        available via properties on the `URL` class.299300        For example:301302        url = httpx.URL("https://www.example.com").copy_with(username="jo@gmail.com", password="a secret")303        assert url == "https://jo%40email.com:a%20secret@www.example.com"304        """305        allowed = {306            "scheme": str,307            "username": str,308            "password": str,309            "userinfo": bytes,310            "host": str,311            "port": int,312            "netloc": str,313            "path": str,314            "query": bytes,315            "raw_path": bytes,316            "fragment": str,317        }318        for key, value in kwargs.items():319            if key not in allowed:320                message = f"{key!r} is an invalid keyword argument for copy_with()"321                raise TypeError(message)322            if value is not None and not isinstance(value, allowed[key]):323                expected = allowed[key].__name__324                seen = type(value).__name__325                message = f"Argument {key!r} must be {expected} but got {seen}"326                raise TypeError(message)327328        # Replace username, password, userinfo, host, port, netloc with "authority" for rfc3986329        if "username" in kwargs or "password" in kwargs:330            # Consolidate username and password into userinfo.331            username = quote(kwargs.pop("username", self.username) or "")332            password = quote(kwargs.pop("password", self.password) or "")333            userinfo = f"{username}:{password}" if password else username334            kwargs["userinfo"] = userinfo.encode("ascii")335336        if "host" in kwargs or "port" in kwargs:337            # Consolidate host and port into  netloc.338            host = kwargs.pop("host", self.host) or ""339            port = kwargs.pop("port", self.port)340            kwargs["netloc"] = f"{host}:{port}" if port is not None else host341342        if "userinfo" in kwargs or "netloc" in kwargs:343            # Consolidate userinfo and netloc into authority.344            userinfo = (kwargs.pop("userinfo", self.userinfo) or b"").decode("ascii")345            netloc = kwargs.pop("netloc", self.netloc) or ""346            authority = f"{userinfo}@{netloc}" if userinfo else netloc347            kwargs["authority"] = authority348349        if "raw_path" in kwargs:350            raw_path = kwargs.pop("raw_path") or b""351            path, has_query, query = raw_path.decode("ascii").partition("?")352            kwargs["path"] = path353            kwargs["query"] = query if has_query else None354355        else:356            # Ensure path=<url quoted str> for rfc3986357            if kwargs.get("path") is not None:358                kwargs["path"] = quote(kwargs["path"])359360            # Ensure query=<str> for rfc3986361            if kwargs.get("query") is not None:362                kwargs["query"] = kwargs["query"].decode("ascii")363364        return URL(self._uri_reference.copy_with(**kwargs).unsplit())365366    def join(self, url: URLTypes) -> "URL":367        """368        Return an absolute URL, using this URL as the base.369370        Eg.371372        url = httpx.URL("https://www.example.com/test")373        url = url.join("/new/path")374        assert url == "https://www.example.com/test/new/path"375        """376        if self.is_relative_url:377            return URL(url)378379        # We drop any fragment portion, because RFC 3986 strictly380        # treats URLs with a fragment portion as not being absolute URLs.381        base_uri = self._uri_reference.copy_with(fragment=None)382        relative_url = URL(url)383        return URL(relative_url._uri_reference.resolve_with(base_uri).unsplit())384385    def __hash__(self) -> int:386        return hash(str(self))387388    def __eq__(self, other: typing.Any) -> bool:389        return isinstance(other, (URL, str)) and str(self) == str(other)390391    def __str__(self) -> str:392        return self._uri_reference.unsplit()393394    def __repr__(self) -> str:395        class_name = self.__class__.__name__396        url_str = str(self)397        if self._uri_reference.userinfo:398            username = quote(self.username)399            url_str = (400                rfc3986.urlparse(url_str)401                .copy_with(userinfo=f"{username}:[secure]")402                .unsplit()403            )404        return f"{class_name}({url_str!r})"405406407class QueryParams(typing.Mapping[str, str]):408    """409    URL query parameters, as a multi-dict.410    """411412    def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:413        assert len(args) < 2, "Too many arguments."414        assert not (args and kwargs), "Cannot mix named and unnamed arguments."415416        value = args[0] if args else kwargs417418        items: typing.Sequence[typing.Tuple[str, PrimitiveData]]419        if value is None or isinstance(value, (str, bytes)):420            value = value.decode("ascii") if isinstance(value, bytes) else value421            items = parse_qsl(value)422        elif isinstance(value, QueryParams):423            items = value.multi_items()424        elif isinstance(value, list):425            items = value426        else:427            items = flatten_queryparams(value)428429        self._list = [(str(k), str_query_param(v)) for k, v in items]430        self._dict = {str(k): str_query_param(v) for k, v in items}431432    def keys(self) -> typing.KeysView:433        return self._dict.keys()434435    def values(self) -> typing.ValuesView:436        return self._dict.values()437438    def items(self) -> typing.ItemsView:439        """440        Return all items in the query params. If a key occurs more than once441        only the first item for that key is returned.442        """443        return self._dict.items()444445    def multi_items(self) -> typing.List[typing.Tuple[str, str]]:446        """447        Return all items in the query params. Allow duplicate keys to occur.448        """449        return list(self._list)450451    def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:452        """453        Get a value from the query param for a given key. If the key occurs454        more than once, then only the first value is returned.455        """456        if key in self._dict:457            return self._dict[key]458        return default459460    def get_list(self, key: typing.Any) -> typing.List[str]:461        """462        Get all values from the query param for a given key.463        """464        return [item_value for item_key, item_value in self._list if item_key == key]465466    def update(self, params: QueryParamTypes = None) -> None:467        if not params:468            return469470        params = QueryParams(params)471        for param in params:472            item, *extras = params.get_list(param)473            self[param] = item474            if extras:475                self._list.extend((param, e) for e in extras)476                # ensure getter matches merged QueryParams getter477                self._dict[param] = params[param]478479    def __getitem__(self, key: typing.Any) -> str:480        return self._dict[key]481482    def __setitem__(self, key: str, value: str) -> None:483        self._dict[key] = value484485        found_indexes = []486        for idx, (item_key, _) in enumerate(self._list):487            if item_key == key:488                found_indexes.append(idx)489490        for idx in reversed(found_indexes[1:]):491            del self._list[idx]492493        if found_indexes:494            idx = found_indexes[0]495            self._list[idx] = (key, value)496        else:497            self._list.append((key, value))498499    def __contains__(self, key: typing.Any) -> bool:500        return key in self._dict501502    def __iter__(self) -> typing.Iterator[typing.Any]:503        return iter(self.keys())504505    def __len__(self) -> int:506        return len(self._dict)507508    def __eq__(self, other: typing.Any) -> bool:509        if not isinstance(other, self.__class__):510            return False511        return sorted(self._list) == sorted(other._list)512513    def __str__(self) -> str:514        return urlencode(self._list)515516    def __repr__(self) -> str:517        class_name = self.__class__.__name__518        query_string = str(self)519        return f"{class_name}({query_string!r})"520521522class Headers(typing.MutableMapping[str, str]):523    """524    HTTP headers, as a case-insensitive multi-dict.525    """526527    def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:528        if headers is None:529            self._list = []  # type: typing.List[typing.Tuple[bytes, bytes]]530        elif isinstance(headers, Headers):531            self._list = list(headers.raw)532        elif isinstance(headers, dict):533            self._list = [534                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))535                for k, v in headers.items()536            ]537        else:538            self._list = [539                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))540                for k, v in headers541            ]542543        self._dict = {}  # type: typing.Dict[bytes, bytes]544        for key, value in self._list:545            if key in self._dict:546                self._dict[key] = self._dict[key] + b", " + value547            else:548                self._dict[key] = value549550        self._encoding = encoding551552    @property553    def encoding(self) -> str:554        """555        Header encoding is mandated as ascii, but we allow fallbacks to utf-8556        or iso-8859-1.557        """558        if self._encoding is None:559            for encoding in ["ascii", "utf-8"]:560                for key, value in self.raw:561                    try:562                        key.decode(encoding)563                        value.decode(encoding)564                    except UnicodeDecodeError:565                        break566                else:567                    # The else block runs if 'break' did not occur, meaning568                    # all values fitted the encoding.569                    self._encoding = encoding570                    break571            else:572                # The ISO-8859-1 encoding covers all 256 code points in a byte,573                # so will never raise decode errors.574                self._encoding = "iso-8859-1"575        return self._encoding576577    @encoding.setter578    def encoding(self, value: str) -> None:579        self._encoding = value580581    @property582    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:583        """584        Returns a list of the raw header items, as byte pairs.585        """586        return list(self._list)587588    def keys(self) -> typing.KeysView[str]:589        return {key.decode(self.encoding): None for key in self._dict.keys()}.keys()590591    def values(self) -> typing.ValuesView[str]:592        return {593            key: value.decode(self.encoding) for key, value in self._dict.items()594        }.values()595596    def items(self) -> typing.ItemsView[str, str]:597        """598        Return `(key, value)` items of headers. Concatenate headers599        into a single comma seperated value when a key occurs multiple times.600        """601        return {602            key.decode(self.encoding): value.decode(self.encoding)603            for key, value in self._dict.items()604        }.items()605606    def multi_items(self) -> typing.List[typing.Tuple[str, str]]:607        """608        Return a list of `(key, value)` pairs of headers. Allow multiple609        occurences of the same key without concatenating into a single610        comma seperated value.611        """612        return [613            (key.decode(self.encoding), value.decode(self.encoding))614            for key, value in self._list615        ]616617    def get(self, key: str, default: typing.Any = None) -> typing.Any:618        """619        Return a header value. If multiple occurences of the header occur620        then concatenate them together with commas.621        """622        try:623            return self[key]624        except KeyError:625            return default626627    def get_list(self, key: str, split_commas: bool = False) -> typing.List[str]:628        """629        Return a list of all header values for a given key.630        If `split_commas=True` is passed, then any comma seperated header631        values are split into multiple return strings.632        """633        get_header_key = key.lower().encode(self.encoding)634635        values = [636            item_value.decode(self.encoding)637            for item_key, item_value in self._list638            if item_key == get_header_key639        ]640641        if not split_commas:642            return values643644        split_values = []645        for value in values:646            split_values.extend([item.strip() for item in value.split(",")])647        return split_values648649    def update(self, headers: HeaderTypes = None) -> None:  # type: ignore650        headers = Headers(headers)651        for header in headers:652            self[header] = headers[header]653654    def copy(self) -> "Headers":655        return Headers(dict(self.items()), encoding=self.encoding)656657    def __getitem__(self, key: str) -> str:658        """659        Return a single header value.660661        If there are multiple headers with the same key, then we concatenate662        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2663        """664        normalized_key = key.lower().encode(self.encoding)665666        items = []667        for header_key, header_value in self._list:668            if header_key == normalized_key:669                items.append(header_value.decode(self.encoding))670671        if items:672            return ", ".join(items)673674        raise KeyError(key)675676    def __setitem__(self, key: str, value: str) -> None:677        """678        Set the header `key` to `value`, removing any duplicate entries.679        Retains insertion order.680        """681        set_key = key.lower().encode(self._encoding or "utf-8")682        set_value = value.encode(self._encoding or "utf-8")683684        self._dict[set_key] = set_value685686        found_indexes = []687        for idx, (item_key, _) in enumerate(self._list):688            if item_key == set_key:689                found_indexes.append(idx)690691        for idx in reversed(found_indexes[1:]):692            del self._list[idx]693694        if found_indexes:695            idx = found_indexes[0]696            self._list[idx] = (set_key, set_value)697        else:698            self._list.append((set_key, set_value))699700    def __delitem__(self, key: str) -> None:701        """702        Remove the header `key`.703        """704        del_key = key.lower().encode(self.encoding)705706        del self._dict[del_key]707708        pop_indexes = []709        for idx, (item_key, _) in enumerate(self._list):710            if item_key == del_key:711                pop_indexes.append(idx)712713        for idx in reversed(pop_indexes):714            del self._list[idx]715716    def __contains__(self, key: typing.Any) -> bool:717        header_key = key.lower().encode(self.encoding)718        return header_key in self._dict719720    def __iter__(self) -> typing.Iterator[typing.Any]:721        return iter(self.keys())722723    def __len__(self) -> int:724        return len(self._list)725726    def __eq__(self, other: typing.Any) -> bool:727        try:728            other_headers = Headers(other)729        except ValueError:730            return False731        return sorted(self._list) == sorted(other_headers._list)732733    def __repr__(self) -> str:734        class_name = self.__class__.__name__735736        encoding_str = ""737        if self.encoding != "ascii":738            encoding_str = f", encoding={self.encoding!r}"739740        as_list = list(obfuscate_sensitive_headers(self.multi_items()))741        as_dict = dict(as_list)742743        no_duplicate_keys = len(as_dict) == len(as_list)744        if no_duplicate_keys:745            return f"{class_name}({as_dict!r}{encoding_str})"746        return f"{class_name}({as_list!r}{encoding_str})"747748749class Request:750    def __init__(751        self,752        method: typing.Union[str, bytes],753        url: typing.Union["URL", str, RawURL],754        *,755        params: QueryParamTypes = None,756        headers: HeaderTypes = None,757        cookies: CookieTypes = None,758        content: RequestContent = None,759        data: RequestData = None,760        files: RequestFiles = None,761        json: typing.Any = None,762        stream: ByteStream = None,763    ):764        if isinstance(method, bytes):765            self.method = method.decode("ascii").upper()766        else:767            self.method = method.upper()768        self.url = URL(url, params=params)769        self.headers = Headers(headers)770        if cookies:771            Cookies(cookies).set_cookie_header(self)772773        if stream is not None:774            # There's an important distinction between `Request(content=...)`,775            # and `Request(stream=...)`.776            #777            # Using `content=...` implies automatically populated content headers,778            # of either `Content-Length: ...` or `Transfer-Encoding: chunked`.779            #780            # Using `stream=...` will not automatically include any content headers.781            #782            # As an end-user you don't really need `stream=...`. It's only783            # useful when:784            #785            # * Preserving the request stream when copying requests, eg for redirects.786            # * Creating request instances on the *server-side* of the transport API.787            self.stream = stream788            self._prepare({})789        else:790            headers, stream = encode_request(content, data, files, json)791            self._prepare(headers)792            self.stream = stream793794    def _prepare(self, default_headers: typing.Dict[str, str]) -> None:795        for key, value in default_headers.items():796            # Ignore Transfer-Encoding if the Content-Length has been set explicitly.797            if key.lower() == "transfer-encoding" and "content-length" in self.headers:798                continue799            self.headers.setdefault(key, value)800801        auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []802803        has_host = "host" in self.headers804        has_content_length = (805            "content-length" in self.headers or "transfer-encoding" in self.headers806        )807808        if not has_host and self.url.host:809            default_port = {"http": 80, "https": 443}.get(self.url.scheme)810            if self.url.port is None or self.url.port == default_port:811                host_header = self.url.host.encode("ascii")812            else:813                host_header = self.url.netloc.encode("ascii")814            auto_headers.append((b"host", host_header))815        if not has_content_length and self.method in ("POST", "PUT", "PATCH"):816            auto_headers.append((b"content-length", b"0"))817818        self.headers = Headers(auto_headers + self.headers.raw)819820    @property821    def content(self) -> bytes:822        if not hasattr(self, "_content"):823            raise RequestNotRead()824        return self._content825826    def read(self) -> bytes:827        """828        Read and return the request content.829        """830        if not hasattr(self, "_content"):831            assert isinstance(self.stream, typing.Iterable)832            self._content = b"".join(self.stream)833            # If a streaming request has been read entirely into memory, then834            # we can replace the stream with a raw bytes implementation,835            # to ensure that any non-replayable streams can still be used.836            self.stream = PlainByteStream(self._content)837        return self._content838839    async def aread(self) -> bytes:840        """841        Read and return the request content.842        """843        if not hasattr(self, "_content"):844            assert isinstance(self.stream, typing.AsyncIterable)845            self._content = b"".join([part async for part in self.stream])846            # If a streaming request has been read entirely into memory, then847            # we can replace the stream with a raw bytes implementation,848            # to ensure that any non-replayable streams can still be used.849            self.stream = PlainByteStream(self._content)850        return self._content851852    def __repr__(self) -> str:853        class_name = self.__class__.__name__854        url = str(self.url)855        return f"<{class_name}({self.method!r}, {url!r})>"856857858class Response:859    def __init__(860        self,861        status_code: int,862        *,863        headers: HeaderTypes = None,864        content: ResponseContent = None,865        text: str = None,866        html: str = None,867        json: typing.Any = None,868        stream: ByteStream = None,869        request: Request = None,870        ext: dict = None,871        history: typing.List["Response"] = None,872        on_close: typing.Callable = None,873    ):874        self.status_code = status_code875        self.headers = Headers(headers)876877        self._request: typing.Optional[Request] = request878879        # When allow_redirects=False and a redirect is received,880        # the client will set `response.next_request`.881        self.next_request: typing.Optional[Request] = None882883        self.call_next: typing.Optional[typing.Callable] = None884885        self.ext = {} if ext is None else ext886        self.history = [] if history is None else list(history)887        self._on_close = on_close888889        self.is_closed = False890        self.is_stream_consumed = False891892        if stream is not None:893            # There's an important distinction between `Response(content=...)`,894            # and `Response(stream=...)`.895            #896            # Using `content=...` implies automatically populated content headers,897            # of either `Content-Length: ...` or `Transfer-Encoding: chunked`.898            #899            # Using `stream=...` will not automatically include any content headers.900            #901            # As an end-user you don't really need `stream=...`. It's only902            # useful when creating response instances having received a stream903            # from the transport API.904            self.stream = stream905        else:906            headers, stream = encode_response(content, text, html, json)907            self._prepare(headers)908            self.stream = stream909            if content is None or isinstance(content, (bytes, str)):910                # Load the response body, except for streaming content.911                self.read()912913        self._num_bytes_downloaded = 0914915    def _prepare(self, default_headers: typing.Dict[str, str]) -> None:916        for key, value in default_headers.items():917            # Ignore Transfer-Encoding if the Content-Length has been set explicitly.918            if key.lower() == "transfer-encoding" and "content-length" in self.headers:919                continue920            self.headers.setdefault(key, value)921922    @property923    def elapsed(self) -> datetime.timedelta:924        """925        Returns the time taken for the complete request/response926        cycle to complete.927        """928        if not hasattr(self, "_elapsed"):929            raise RuntimeError(930                "'.elapsed' may only be accessed after the response "931                "has been read or closed."932            )933        return self._elapsed934935    @elapsed.setter936    def elapsed(self, elapsed: datetime.timedelta) -> None:937        self._elapsed = elapsed938939    @property940    def request(self) -> Request:941        """942        Returns the request instance associated to the current response.943        """944        if self._request is None:945            raise RuntimeError(946                "The request instance has not been set on this response."947            )948        return self._request949950    @request.setter951    def request(self, value: Request) -> None:952        self._request = value953954    @property955    def http_version(self) -> str:956        return self.ext.get("http_version", "HTTP/1.1")957958    @property959    def reason_phrase(self) -> str:960        return self.ext.get("reason", codes.get_reason_phrase(self.status_code))961962    @property963    def url(self) -> typing.Optional[URL]:964        """965        Returns the URL for which the request was made.966        """967        return self.request.url968969    @property970    def content(self) -> bytes:971        if not hasattr(self, "_content"):972            raise ResponseNotRead()973        return self._content974975    @property976    def text(self) -> str:977        if not hasattr(self, "_text"):978            content = self.content979            if not content:980                self._text = ""981            else:982                decoder = TextDecoder(encoding=self.encoding)983                self._text = "".join([decoder.decode(self.content), decoder.flush()])984        return self._text985986    @property987    def encoding(self) -> typing.Optional[str]:988        """989        Return the encoding, which may have been set explicitly, or may have990        been specified by the Content-Type header.991        """992        if not hasattr(self, "_encoding"):993            encoding = self.charset_encoding994            if encoding is None or not is_known_encoding(encoding):995                self._encoding = None996            else:997                self._encoding = encoding998        return self._encoding9991000    @encoding.setter1001    def encoding(self, value: str) -> None:1002        self._encoding = value10031004    @property1005    def charset_encoding(self) -> typing.Optional[str]:1006        """1007        Return the encoding, as specified by the Content-Type header.1008        """1009        content_type = self.headers.get("Content-Type")1010        if content_type is None:1011            return None10121013        _, params = cgi.parse_header(content_type)1014        if "charset" not in params:1015            return None10161017        return params["charset"].strip("'\"")10181019    def _get_content_decoder(self) -> ContentDecoder:1020        """1021        Returns a decoder instance which can be used to decode the raw byte1022        content, depending on the Content-Encoding used in the response.1023        """1024        if not hasattr(self, "_decoder"):1025            decoders: typing.List[ContentDecoder] = []1026            values = self.headers.get_list("content-encoding", split_commas=True)1027            for value in values:1028                value = value.strip().lower()1029                try:1030                    decoder_cls = SUPPORTED_DECODERS[value]1031                    decoders.append(decoder_cls())1032                except KeyError:1033                    continue10341035            if len(decoders) == 1:1036                self._decoder = decoders[0]1037            elif len(decoders) > 1:1038                self._decoder = MultiDecoder(children=decoders)1039            else:1040                self._decoder = IdentityDecoder()10411042        return self._decoder10431044    @property1045    def is_error(self) -> bool:1046        return codes.is_error(self.status_code)10471048    @property1049    def is_redirect(self) -> bool:1050        return codes.is_redirect(self.status_code) and "location" in self.headers10511052    def raise_for_status(self) -> None:1053        """1054        Raise the `HTTPStatusError` if one occurred.1055        """1056        message = (1057            "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"1058            "For more information check: https://httpstatuses.com/{0.status_code}"1059        )10601061        request = self._request1062        if request is None:1063            raise RuntimeError(1064                "Cannot call `raise_for_status` as the request "1065                "instance has not been set on this response."1066            )10671068        if codes.is_client_error(self.status_code):1069            message = message.format(self, error_type="Client Error")1070            raise HTTPStatusError(message, request=request, response=self)1071        elif codes.is_server_error(self.status_code):1072            message = message.format(self, error_type="Server Error")1073            raise HTTPStatusError(message, request=request, response=self)10741075    def json(self, **kwargs: typing.Any) -> typing.Any:1076        if self.charset_encoding is None and self.content and len(self.content) > 3:1077            encoding = guess_json_utf(self.content)1078            if encoding is not None:1079                try:1080                    return jsonlib.loads(self.content.decode(encoding), **kwargs)1081                except UnicodeDecodeError:1082                    pass1083        return jsonlib.loads(self.text, **kwargs)10841085    @property1086    def cookies(self) -> "Cookies":1087        if not hasattr(self, "_cookies"):1088            self._cookies = Cookies()1089            self._cookies.extract_cookies(self)1090        return self._cookies10911092    @property1093    def links(self) -> typing.Dict[typing.Optional[str], typing.Dict[str, str]]:1094        """1095        Returns the parsed header links of the response, if any1096        """1097        header = self.headers.get("link")1098        ldict = {}1099        if header:1100            links = parse_header_links(header)1101            for link in links:1102                key = link.get("rel") or link.get("url")1103                ldict[key] = link1104        return ldict11051106    @property1107    def num_bytes_downloaded(self) -> int:1108        return self._num_bytes_downloaded11091110    def __repr__(self) -> str:1111        return f"<Response [{self.status_code} {self.reason_phrase}]>"11121113    @contextlib.contextmanager1114    def _wrap_decoder_errors(self) -> typing.Iterator[None]:1115        # If the response has an associated request instance, we want decoding1116        # errors to be raised as proper `httpx.DecodingError` exceptions.1117        try:1118            yield1119        except ValueError as exc:1120            if self._request is None:1121                raise exc1122            raise DecodingError(message=str(exc), request=self.request) from exc11231124    def read(self) -> bytes:1125        """1126        Read and return the response content.1127        """1128        if not hasattr(self, "_content"):1129            self._content = b"".join(self.iter_bytes())1130        return self._content11311132    def iter_bytes(self) -> typing.Iterator[bytes]:1133        """1134        A byte-iterator over the decoded response content.1135        This allows us to handle gzip, deflate, and brotli encoded responses.1136        """1137        if hasattr(self, "_content"):1138            yield self._content1139        else:1140            decoder = self._get_content_decoder()1141            with self._wrap_decoder_errors():1142                for chunk in self.iter_raw():1143                    yield decoder.decode(chunk)1144                yield decoder.flush()11451146    def iter_text(self) -> typing.Iterator[str]:1147        """1148        A str-iterator over the decoded response content1149        that handles both gzip, deflate, etc but also detects the content's1150        string encoding.1151        """1152        decoder = TextDecoder(encoding=self.encoding)1153        with self._wrap_decoder_errors():1154            for chunk in self.iter_bytes():1155                yield decoder.decode(chunk)1156            yield decoder.flush()11571158    def iter_lines(self) -> typing.Iterator[str]:1159        decoder = LineDecoder()1160        with self._wrap_decoder_errors():1161            for text in self.iter_text():1162                for line in decoder.decode(text):1163                    yield line1164            for line in decoder.flush():1165                yield line11661167    def iter_raw(self) -> typing.Iterator[bytes]:1168        """1169        A byte-iterator over the raw response content.1170        """1171        if self.is_stream_consumed:1172            raise StreamConsumed()1173        if self.is_closed:1174            raise ResponseClosed()1175        if not isinstance(self.stream, typing.Iterable):1176            raise RuntimeError("Attempted to call a sync iterator on an async stream.")11771178        self.is_stream_consumed = True1179        self._num_bytes_downloaded = 01180        with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1181            for part in self.stream:1182                self._num_bytes_downloaded += len(part)1183                yield part1184        self.close()11851186    def next(self) -> "Response":1187        """1188        Get the next response from a redirect response.1189        """1190        if not self.is_redirect:1191            message = (1192                "Called .next(), but the response was not a redirect. "1193                "Calling code should check `response.is_redirect` first."1194            )1195            raise NotRedirectResponse(message)1196        assert self.call_next is not None1197        return self.call_next()11981199    def close(self) -> None:1200        """1201        Close the response and release the connection.1202        Automatically called if the response body is read to completion.1203        """1204        if not self.is_closed:1205            self.is_closed = True1206            if self._on_close is not None:1207                self._on_close(self)12081209    async def aread(self) -> bytes:1210        """1211        Read and return the response content.1212        """1213        if not hasattr(self, "_content"):1214            self._content = b"".join([part async for part in self.aiter_bytes()])1215        return self._content12161217    async def aiter_bytes(self) -> typing.AsyncIterator[bytes]:1218        """1219        A byte-iterator over the decoded response content.1220        This allows us to handle gzip, deflate, and brotli encoded responses.1221        """1222        if hasattr(self, "_content"):1223            yield self._content1224        else:1225            decoder = self._get_content_decoder()1226            with self._wrap_decoder_errors():1227                async for chunk in self.aiter_raw():1228                    yield decoder.decode(chunk)1229                yield decoder.flush()12301231    async def aiter_text(self) -> typing.AsyncIterator[str]:1232        """1233        A str-iterator over the decoded response content1234        that handles both gzip, deflate, etc but also detects the content's1235        string encoding.1236        """1237        decoder = TextDecoder(encoding=self.encoding)1238        with self._wrap_decoder_errors():1239            async for chunk in self.aiter_bytes():1240                yield decoder.decode(chunk)1241            yield decoder.flush()12421243    async def aiter_lines(self) -> typing.AsyncIterator[str]:1244        decoder = LineDecoder()1245        with self._wrap_decoder_errors():1246            async for text in self.aiter_text():1247                for line in decoder.decode(text):1248                    yield line1249            for line in decoder.flush():1250                yield line12511252    async def aiter_raw(self) -> typing.AsyncIterator[bytes]:1253        """1254        A byte-iterator over the raw response content.1255        """1256        if self.is_stream_consumed:1257            raise StreamConsumed()1258        if self.is_closed:1259            raise ResponseClosed()1260        if not isinstance(self.stream, typing.AsyncIterable):1261            raise RuntimeError("Attempted to call a async iterator on a sync stream.")12621263        self.is_stream_consumed = True1264        self._num_bytes_downloaded = 01265        with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1266            async for part in self.stream:1267                self._num_bytes_downloaded += len(part)1268                yield part1269        await self.aclose()12701271    async def anext(self) -> "Response":1272        """1273        Get the next response from a redirect response.1274        """1275        if not self.is_redirect:1276            raise NotRedirectResponse(1277                "Called .anext(), but the response was not a redirect. "1278                "Calling code should check `response.is_redirect` first."1279            )1280        assert self.call_next is not None1281        return await self.call_next()12821283    async def aclose(self) -> None:1284        """1285        Close the response and release the connection.1286        Automatically called if the response body is read to completion.1287        """1288        if not self.is_closed:1289            self.is_closed = True1290            if self._on_close is not None:1291                await self._on_close(self)129212931294class Cookies(MutableMapping):1295    """1296    HTTP Cookies, as a mutable mapping.1297    """12981299    def __init__(self, cookies: CookieTypes = None) -> None:1300        if cookies is None or isinstance(cookies, dict):1301            self.jar = CookieJar()1302            if isinstance(cookies, dict):1303                for key, value in cookies.items():1304                    self.set(key, value)1305        elif isinstance(cookies, list):1306            self.jar = CookieJar()1307            for key, value in cookies:1308                self.set(key, value)1309        elif isinstance(cookies, Cookies):1310            self.jar = CookieJar()1311            for cookie in cookies.jar:1312                self.jar.set_cookie(cookie)1313        else:1314            self.jar = cookies13151316    def extract_cookies(self, response: Response) -> None:1317        """1318        Loads any cookies based on the response `Set-Cookie` headers.1319        """1320        urlib_response = self._CookieCompatResponse(response)1321        urllib_request = self._CookieCompatRequest(response.request)13221323        self.jar.extract_cookies(urlib_response, urllib_request)  # type: ignore13241325    def set_cookie_header(self, request: Request) -> None:1326        """1327        Sets an appropriate 'Cookie:' HTTP header on the `Request`.1328        """1329        urllib_request = self._CookieCompatRequest(request)1330        self.jar.add_cookie_header(urllib_request)13311332    def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:1333        """1334        Set a cookie value by name. May optionally include domain and path.1335        """1336        kwargs = {1337            "version": 0,1338            "name": name,1339            "value": value,1340            "port": None,1341            "port_specified": False,1342            "domain": domain,1343            "domain_specified": bool(domain),1344            "domain_initial_dot": domain.startswith("."),1345            "path": path,1346            "path_specified": bool(path),1347            "secure": False,1348            "expires": None,1349            "discard": True,1350            "comment": None,1351            "comment_url": None,1352            "rest": {"HttpOnly": None},1353            "rfc2109": False,1354        }1355        cookie = Cookie(**kwargs)  # type: ignore1356        self.jar.set_cookie(cookie)13571358    def get(  # type: ignore1359        self, name: str, default: str = None, domain: str = None, path: str = None1360    ) -> typing.Optional[str]:1361        """1362        Get a cookie by name. May optionally include domain and path1363        in order to specify exactly which cookie to retrieve.1364        """1365        value = None1366        for cookie in self.jar:1367            if cookie.name == name:1368                if domain is None or cookie.domain == domain:1369                    if path is None or cookie.path == path:1370                        if value is not None:1371                            message = f"Multiple cookies exist with name={name}"1372                            raise CookieConflict(message)1373                        value = cookie.value13741375        if value is None:1376            return default1377        return value13781379    def delete(self, name: str, domain: str = None, path: str = None) -> None:1380        """1381        Delete a cookie by name. May optionally include domain and path1382        in order to specify exactly which cookie to delete.1383        """1384        if domain is not None and path is not None:1385            return self.jar.clear(domain, path, name)13861387        remove = []1388        for cookie in self.jar:1389            if cookie.name == name:1390                if domain is None or cookie.domain == domain:1391                    if path is None or cookie.path == path:1392                        remove.append(cookie)13931394        for cookie in remove:1395            self.jar.clear(cookie.domain, cookie.path, cookie.name)13961397    def clear(self, domain: str = None, path: str = None) -> None:1398        """1399        Delete all cookies. Optionally include a domain and path in1400        order to only delete a subset of all the cookies.1401        """1402        args = []1403        if domain is not None:1404            args.append(domain)1405        if path is not None:1406            assert domain is not None1407            args.append(path)1408        self.jar.clear(*args)14091410    def update(self, cookies: CookieTypes = None) -> None:  # type: ignore1411        cookies = Cookies(cookies)1412        for cookie in cookies.jar:1413            self.jar.set_cookie(cookie)14141415    def __setitem__(self, name: str, value: str) -> None:1416        return self.set(name, value)14171418    def __getitem__(self, name: str) -> str:1419        value = self.get(name)1420        if value is None:1421            raise KeyError(name)1422        return value14231424    def __delitem__(self, name: str) -> None:1425        return self.delete(name)14261427    def __len__(self) -> int:1428        return len(self.jar)14291430    def __iter__(self) -> typing.Iterator[str]:1431        return (cookie.name for cookie in self.jar)14321433    def __bool__(self) -> bool:1434        for _ in self.jar:1435            return True1436        return False14371438    class _CookieCompatRequest(urllib.request.Request):1439        """1440        Wraps a `Request` instance up in a compatibility interface suitable1441        for use with `CookieJar` operations.1442        """14431444        def __init__(self, request: Request) -> None:1445            super().__init__(1446                url=str(request.url),1447                headers=dict(request.headers),1448                method=request.method,1449            )1450            self.request = request14511452        def add_unredirected_header(self, key: str, value: str) -> None:1453            super().add_unredirected_header(key, value)1454            self.request.headers[key] = value14551456    class _CookieCompatResponse:1457        """1458        Wraps a `Request` instance up in a compatibility interface suitable1459        for use with `CookieJar` operations.1460        """14611462        def __init__(self, response: Response):1463            self.response = response14641465        def info(self) -> email.message.Message:1466            info = email.message.Message()1467            for key, value in self.response.headers.multi_items():1468                #  Note that setting `info[key]` here is an "append" operation,1469                # not a "replace" operation.1470                # https://docs.python.org/3/library/email.compat32-message.html#email.message.Message.__setitem__1471                info[key] = value1472            return info