Skip to content
Myr

models.py

This file

Path

http3/models.py

1,145 lines · 35.7 KiB · Python

Last changed by

Int status codes (#92)Tom Christiebefore adoption56a7943

History of this file

Take it

1import cgi2import email.message3import json as jsonlib4import typing5import urllib.request6from collections.abc import MutableMapping7from http.cookiejar import Cookie, CookieJar8from urllib.parse import parse_qsl, urlencode910import chardet11import rfc39861213from .decoders import (14    ACCEPT_ENCODING,15    SUPPORTED_DECODERS,16    Decoder,17    IdentityDecoder,18    MultiDecoder,19)20from .exceptions import (21    CookieConflict,22    HttpError,23    InvalidURL,24    ResponseClosed,25    ResponseNotRead,26    StreamConsumed,27)28from .multipart import multipart_encode29from .status_codes import StatusCode30from .utils import is_known_encoding, normalize_header_key, normalize_header_value3132URLTypes = typing.Union["URL", str]3334QueryParamTypes = typing.Union[35    "QueryParams",36    typing.Mapping[str, str],37    typing.List[typing.Tuple[typing.Any, typing.Any]],38    str,39]4041HeaderTypes = typing.Union[42    "Headers",43    typing.Dict[typing.AnyStr, typing.AnyStr],44    typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],45]4647CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]4849AuthTypes = typing.Union[50    typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],51    typing.Callable[["AsyncRequest"], "AsyncRequest"],52]5354AsyncRequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]5556RequestData = typing.Union[dict, bytes, typing.Iterator[bytes]]5758RequestFiles = typing.Dict[59    str,60    typing.Union[61        typing.IO[typing.AnyStr],  # file62        typing.Tuple[str, typing.IO[typing.AnyStr]],  # (filename, file)63        typing.Tuple[64            str, typing.IO[typing.AnyStr], str65        ],  # (filename, file, content_type)66    ],67]6869AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]7071ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]727374class URL:75    def __init__(76        self,77        url: URLTypes,78        allow_relative: bool = False,79        params: QueryParamTypes = None,80    ) -> None:81        if isinstance(url, rfc3986.uri.URIReference):82            self.components = url83        elif isinstance(url, str):84            self.components = rfc3986.api.uri_reference(url)85        else:86            self.components = url.components8788        # Handle IDNA domain names.89        if self.components.authority:90            idna_authority = self.components.authority.encode("idna").decode("ascii")91            if idna_authority != self.components.authority:92                self.components = self.components.copy_with(authority=idna_authority)9394        # Normalize scheme and domain name.95        self.components = self.components.normalize()9697        # Add any query parameters.98        if params:99            query_string = str(QueryParams(params))100            self.components = self.components.copy_with(query=query_string)101102        # Enforce absolute URLs by default.103        if not allow_relative:104            if not self.scheme:105                raise InvalidURL("No scheme included in URL.")106            if self.scheme not in ("http", "https"):107                raise InvalidURL('URL scheme must be "http" or "https".')108            if not self.host:109                raise InvalidURL("No host included in URL.")110111    @property112    def scheme(self) -> str:113        return self.components.scheme or ""114115    @property116    def authority(self) -> str:117        return self.components.authority or ""118119    @property120    def username(self) -> str:121        userinfo = self.components.userinfo or ""122        return userinfo.partition(":")[0]123124    @property125    def password(self) -> str:126        userinfo = self.components.userinfo or ""127        return userinfo.partition(":")[2]128129    @property130    def host(self) -> str:131        return self.components.host or ""132133    @property134    def port(self) -> int:135        port = self.components.port136        if port is None:137            return {"https": 443, "http": 80}[self.scheme]138        return int(port)139140    @property141    def path(self) -> str:142        return self.components.path or "/"143144    @property145    def query(self) -> str:146        return self.components.query or ""147148    @property149    def full_path(self) -> str:150        path = self.path151        if self.query:152            path += "?" + self.query153        return path154155    @property156    def fragment(self) -> str:157        return self.components.fragment or ""158159    @property160    def is_ssl(self) -> bool:161        return self.components.scheme == "https"162163    @property164    def is_absolute_url(self) -> bool:165        """166        Return `True` for absolute URLs such as 'http://example.com/path',167        and `False` for relative URLs such as '/path'.168        """169        # We don't use rfc3986's `is_absolute` because it treats170        # URLs with a fragment portion as not absolute.171        # What we actually care about is if the URL provides172        # a scheme and hostname to which connections should be made.173        return self.components.scheme and self.components.host174175    @property176    def is_relative_url(self) -> bool:177        return not self.is_absolute_url178179    @property180    def origin(self) -> "Origin":181        return Origin(self)182183    def copy_with(self, **kwargs: typing.Any) -> "URL":184        return URL(self.components.copy_with(**kwargs))185186    def resolve_with(self, base_url: URLTypes) -> "URL":187        """188        Return an absolute URL, using base_url as the base.189        """190        # We drop any fragment portion, because RFC 3986 strictly191        # treats URLs with a fragment portion as not being absolute URLs.192        base_url = URL(base_url).copy_with(fragment=None)193        return URL(self.components.resolve_with(base_url.components))194195    def __hash__(self) -> int:196        return hash(str(self))197198    def __eq__(self, other: typing.Any) -> bool:199        return isinstance(other, URL) and str(self) == str(other)200201    def __str__(self) -> str:202        return self.components.unsplit()203204    def __repr__(self) -> str:205        class_name = self.__class__.__name__206        url_str = str(self)207        return f"{class_name}({url_str!r})"208209210class Origin:211    """212    The URL scheme and authority information, as a comparable, hashable object.213    """214215    def __init__(self, url: URLTypes) -> None:216        if not isinstance(url, URL):217            url = URL(url)218        self.is_ssl = url.is_ssl219        self.host = url.host220        self.port = url.port221222    def __eq__(self, other: typing.Any) -> bool:223        return (224            isinstance(other, self.__class__)225            and self.is_ssl == other.is_ssl226            and self.host == other.host227            and self.port == other.port228        )229230    def __hash__(self) -> int:231        return hash((self.is_ssl, self.host, self.port))232233234class QueryParams(typing.Mapping[str, str]):235    """236    URL query parameters, as a multi-dict.237    """238239    def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:240        assert len(args) < 2, "Too many arguments."241        assert not (args and kwargs), "Cannot mix named and unnamed arguments."242243        value = args[0] if args else kwargs244245        if isinstance(value, str):246            items = parse_qsl(value)247        elif isinstance(value, QueryParams):248            items = value.multi_items()249        elif isinstance(value, list):250            items = value251        else:252            items = value.items()  # type: ignore253254        self._list = [(str(k), str(v)) for k, v in items]255        self._dict = {str(k): str(v) for k, v in items}256257    def getlist(self, key: typing.Any) -> typing.List[str]:258        return [item_value for item_key, item_value in self._list if item_key == key]259260    def keys(self) -> typing.KeysView:261        return self._dict.keys()262263    def values(self) -> typing.ValuesView:264        return self._dict.values()265266    def items(self) -> typing.ItemsView:267        return self._dict.items()268269    def multi_items(self) -> typing.List[typing.Tuple[str, str]]:270        return list(self._list)271272    def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:273        if key in self._dict:274            return self._dict[key]275        return default276277    def __getitem__(self, key: typing.Any) -> str:278        return self._dict[key]279280    def __contains__(self, key: typing.Any) -> bool:281        return key in self._dict282283    def __iter__(self) -> typing.Iterator[typing.Any]:284        return iter(self.keys())285286    def __len__(self) -> int:287        return len(self._dict)288289    def __eq__(self, other: typing.Any) -> bool:290        if not isinstance(other, self.__class__):291            return False292        return sorted(self._list) == sorted(other._list)293294    def __str__(self) -> str:295        return urlencode(self._list)296297    def __repr__(self) -> str:298        class_name = self.__class__.__name__299        query_string = str(self)300        return f"{class_name}({query_string!r})"301302303class Headers(typing.MutableMapping[str, str]):304    """305    HTTP headers, as a case-insensitive multi-dict.306    """307308    def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:309        if headers is None:310            self._list = []  # type: typing.List[typing.Tuple[bytes, bytes]]311        elif isinstance(headers, Headers):312            self._list = list(headers.raw)313        elif isinstance(headers, dict):314            self._list = [315                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))316                for k, v in headers.items()317            ]318        else:319            self._list = [320                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))321                for k, v in headers322            ]323        self._encoding = encoding324325    @property326    def encoding(self) -> str:327        """328        Header encoding is mandated as ascii, but we allow fallbacks to utf-8329        or iso-8859-1.330        """331        if self._encoding is None:332            for encoding in ["ascii", "utf-8"]:333                for key, value in self.raw:334                    try:335                        key.decode(encoding)336                        value.decode(encoding)337                    except UnicodeDecodeError:338                        break339                else:340                    # The else block runs if 'break' did not occur, meaning341                    # all values fitted the encoding.342                    self._encoding = encoding343                    break344            else:345                # The ISO-8859-1 encoding covers all 256 code points in a byte,346                # so will never raise decode errors.347                self._encoding = "iso-8859-1"348        return self._encoding349350    @encoding.setter351    def encoding(self, value: str) -> None:352        self._encoding = value353354    @property355    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:356        """357        Returns a list of the raw header items, as byte pairs.358        May be mutated in-place.359        """360        return self._list361362    def keys(self) -> typing.List[str]:  # type: ignore363        return [key.decode(self.encoding) for key, value in self._list]364365    def values(self) -> typing.List[str]:  # type: ignore366        return [value.decode(self.encoding) for key, value in self._list]367368    def items(self) -> typing.List[typing.Tuple[str, str]]:  # type: ignore369        return [370            (key.decode(self.encoding), value.decode(self.encoding))371            for key, value in self._list372        ]373374    def get(self, key: str, default: typing.Any = None) -> typing.Any:375        try:376            return self[key]377        except KeyError:378            return default379380    def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:381        """382        Return multiple header values.383        """384        get_header_key = key.lower().encode(self.encoding)385386        values = [387            item_value.decode(self.encoding)388            for item_key, item_value in self._list389            if item_key == get_header_key390        ]391392        if not split_commas:393            return values394395        split_values = []396        for value in values:397            split_values.extend([item.strip() for item in value.split(",")])398        return split_values399400    def __getitem__(self, key: str) -> str:401        """402        Return a single header value.403404        If there are multiple headers with the same key, then we concatenate405        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2406        """407        normalized_key = key.lower().encode(self.encoding)408409        items = []410        for header_key, header_value in self._list:411            if header_key == normalized_key:412                items.append(header_value.decode(self.encoding))413414        if items:415            return ", ".join(items)416417        raise KeyError(key)418419    def __setitem__(self, key: str, value: str) -> None:420        """421        Set the header `key` to `value`, removing any duplicate entries.422        Retains insertion order.423        """424        set_key = key.lower().encode(self.encoding)425        set_value = value.encode(self.encoding)426427        found_indexes = []428        for idx, (item_key, item_value) in enumerate(self._list):429            if item_key == set_key:430                found_indexes.append(idx)431432        for idx in reversed(found_indexes[1:]):433            del self._list[idx]434435        if found_indexes:436            idx = found_indexes[0]437            self._list[idx] = (set_key, set_value)438        else:439            self._list.append((set_key, set_value))440441    def __delitem__(self, key: str) -> None:442        """443        Remove the header `key`.444        """445        del_key = key.lower().encode(self.encoding)446447        pop_indexes = []448        for idx, (item_key, item_value) in enumerate(self._list):449            if item_key == del_key:450                pop_indexes.append(idx)451452        for idx in reversed(pop_indexes):453            del self._list[idx]454455    def __contains__(self, key: typing.Any) -> bool:456        get_header_key = key.lower().encode(self.encoding)457        for header_key, header_value in self._list:458            if header_key == get_header_key:459                return True460        return False461462    def __iter__(self) -> typing.Iterator[typing.Any]:463        return iter(self.keys())464465    def __len__(self) -> int:466        return len(self._list)467468    def __eq__(self, other: typing.Any) -> bool:469        if not isinstance(other, Headers):470            return False471        return sorted(self._list) == sorted(other._list)472473    def __repr__(self) -> str:474        class_name = self.__class__.__name__475476        encoding_str = ""477        if self.encoding != "ascii":478            encoding_str = f", encoding={self.encoding!r}"479480        as_dict = dict(self.items())481        if len(as_dict) == len(self):482            return f"{class_name}({as_dict!r}{encoding_str})"483        as_list = self.items()484        return f"{class_name}({as_list!r}{encoding_str})"485486487class BaseRequest:488    def __init__(489        self,490        method: str,491        url: typing.Union[str, URL],492        *,493        params: QueryParamTypes = None,494        headers: HeaderTypes = None,495        cookies: CookieTypes = None,496    ):497        self.method = method.upper()498        self.url = URL(url, params=params)499        self.headers = Headers(headers)500        if cookies:501            self._cookies = Cookies(cookies)502            self._cookies.set_cookie_header(self)503504    def encode_data(505        self, data: dict = None, files: RequestFiles = None, json: typing.Any = None506    ) -> typing.Tuple[bytes, str]:507        if json is not None:508            content = jsonlib.dumps(json).encode("utf-8")509            content_type = "application/json"510        elif files is not None:511            content, content_type = multipart_encode(data or {}, files)512        elif data is not None:513            content = urlencode(data, doseq=True).encode("utf-8")514            content_type = "application/x-www-form-urlencoded"515        else:516            content = b""517            content_type = ""518        return content, content_type519520    def prepare(self) -> None:521        content = getattr(self, "content", None)  # type: bytes522        is_streaming = getattr(self, "is_streaming", False)523524        auto_headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]525526        has_user_agent = "user-agent" in self.headers527        has_accept = "accept" in self.headers528        has_content_length = (529            "content-length" in self.headers or "transfer-encoding" in self.headers530        )531        has_accept_encoding = "accept-encoding" in self.headers532533        if not has_user_agent:534            auto_headers.append((b"user-agent", b"http3"))535        if not has_accept:536            auto_headers.append((b"accept", b"*/*"))537        if not has_content_length:538            if is_streaming:539                auto_headers.append((b"transfer-encoding", b"chunked"))540            elif content:541                content_length = str(len(content)).encode()542                auto_headers.append((b"content-length", content_length))543        if not has_accept_encoding:544            auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))545546        for item in reversed(auto_headers):547            self.headers.raw.insert(0, item)548549    @property550    def cookies(self) -> "Cookies":551        if not hasattr(self, "_cookies"):552            self._cookies = Cookies()553        return self._cookies554555    def __repr__(self) -> str:556        class_name = self.__class__.__name__557        url = str(self.url)558        return f"<{class_name}({self.method!r}, {url!r})>"559560561class AsyncRequest(BaseRequest):562    def __init__(563        self,564        method: str,565        url: typing.Union[str, URL],566        *,567        params: QueryParamTypes = None,568        headers: HeaderTypes = None,569        cookies: CookieTypes = None,570        data: AsyncRequestData = None,571        files: RequestFiles = None,572        json: typing.Any = None,573    ):574        super().__init__(575            method=method, url=url, params=params, headers=headers, cookies=cookies576        )577578        if data is None or isinstance(data, dict):579            content, content_type = self.encode_data(data, files, json)580            self.is_streaming = False581            self.content = content582            if content_type:583                self.headers["Content-Type"] = content_type584        elif isinstance(data, bytes):585            self.is_streaming = False586            self.content = data587        else:588            assert hasattr(data, "__aiter__")589            self.is_streaming = True590            self.content_aiter = data591592        self.prepare()593594    async def read(self) -> bytes:595        """596        Read and return the response content.597        """598        if not hasattr(self, "content"):599            self.content = b"".join([part async for part in self.stream()])600        return self.content601602    async def stream(self) -> typing.AsyncIterator[bytes]:603        if self.is_streaming:604            async for part in self.content_aiter:605                yield part606        elif self.content:607            yield self.content608609610class Request(BaseRequest):611    def __init__(612        self,613        method: str,614        url: typing.Union[str, URL],615        *,616        params: QueryParamTypes = None,617        headers: HeaderTypes = None,618        cookies: CookieTypes = None,619        data: RequestData = None,620        files: RequestFiles = None,621        json: typing.Any = None,622    ):623        super().__init__(624            method=method, url=url, params=params, headers=headers, cookies=cookies625        )626627        if data is None or isinstance(data, dict):628            content, content_type = self.encode_data(data, files, json)629            self.is_streaming = False630            self.content = content631            if content_type:632                self.headers["Content-Type"] = content_type633        elif isinstance(data, bytes):634            self.is_streaming = False635            self.content = data636        else:637            assert hasattr(data, "__iter__")638            self.is_streaming = True639            self.content_iter = data640641        self.prepare()642643    def read(self) -> bytes:644        if not hasattr(self, "content"):645            self.content = b"".join([part for part in self.stream()])646        return self.content647648    def stream(self) -> typing.Iterator[bytes]:649        if self.is_streaming:650            for part in self.content_iter:651                yield part652        elif self.content:653            yield self.content654655656class BaseResponse:657    def __init__(658        self,659        status_code: int,660        *,661        protocol: str = None,662        headers: HeaderTypes = None,663        request: BaseRequest = None,664        on_close: typing.Callable = None,665    ):666        self.status_code = status_code667        self.protocol = protocol668        self.headers = Headers(headers)669670        self.request = request671        self.on_close = on_close672        self.next = None  # typing.Optional[typing.Callable]673674    @property675    def reason_phrase(self) -> str:676        return StatusCode.get_reason_phrase(self.status_code)677678    @property679    def url(self) -> typing.Optional[URL]:680        """681        Returns the URL for which the request was made.682683        Requires that `request` was provided when instantiating the response.684        """685        return None if self.request is None else self.request.url686687    @property688    def content(self) -> bytes:689        if not hasattr(self, "_content"):690            if hasattr(self, "_raw_content"):691                raw_content = getattr(self, "_raw_content")  # type: bytes692                content = self.decoder.decode(raw_content)693                content += self.decoder.flush()694                self._content = content695            else:696                raise ResponseNotRead()697        return self._content698699    @property700    def text(self) -> str:701        if not hasattr(self, "_text"):702            content = self.content703            if not content:704                self._text = ""705            else:706                encoding = self.encoding707                self._text = content.decode(encoding, errors="replace")708        return self._text709710    @property711    def encoding(self) -> str:712        if not hasattr(self, "_encoding"):713            encoding = self.charset_encoding714            if encoding is None or not is_known_encoding(encoding):715                encoding = self.apparent_encoding716                if encoding is None or not is_known_encoding(encoding):717                    encoding = "utf-8"718            self._encoding = encoding719        return self._encoding720721    @encoding.setter722    def encoding(self, value: str) -> None:723        self._encoding = value724725    @property726    def charset_encoding(self) -> typing.Optional[str]:727        """728        Return the encoding, as specified by the Content-Type header.729        """730        content_type = self.headers.get("Content-Type")731        if content_type is None:732            return None733734        parsed = cgi.parse_header(content_type)735        media_type, params = parsed[0], parsed[-1]736        if "charset" in params:737            return params["charset"].strip("'\"")738739        # RFC 2616 specifies that 'iso-8859-1' should be used as the default740        # for 'text/*' media types, if no charset is provided.741        # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1742        if media_type.startswith("text/"):743            return "iso-8859-1"744745        return None746747    @property748    def apparent_encoding(self) -> typing.Optional[str]:749        """750        Return the encoding, as it appears to autodetection.751        """752        return chardet.detect(self.content)["encoding"]753754    @property755    def decoder(self) -> Decoder:756        """757        Returns a decoder instance which can be used to decode the raw byte758        content, depending on the Content-Encoding used in the response.759        """760        if not hasattr(self, "_decoder"):761            decoders = []  # type: typing.List[Decoder]762            values = self.headers.getlist("content-encoding", split_commas=True)763            for value in values:764                value = value.strip().lower()765                decoder_cls = SUPPORTED_DECODERS[value]766                decoders.append(decoder_cls())767768            if len(decoders) == 1:769                self._decoder = decoders[0]770            elif len(decoders) > 1:771                self._decoder = MultiDecoder(decoders)772            else:773                self._decoder = IdentityDecoder()774775        return self._decoder776777    @property778    def is_redirect(self) -> bool:779        return StatusCode.is_redirect(self.status_code) and "location" in self.headers780781    def raise_for_status(self) -> None:782        """783        Raise the `HttpError` if one occurred.784        """785        message = (786            "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"787            "For more information check: https://httpstatuses.com/{0.status_code}"788        )789790        if StatusCode.is_client_error(self.status_code):791            message = message.format(self, error_type="Client Error")792        elif StatusCode.is_server_error(self.status_code):793            message = message.format(self, error_type="Server Error")794        else:795            message = ""796797        if message:798            raise HttpError(message)799800    def json(self) -> typing.Any:801        return jsonlib.loads(self.content.decode("utf-8"))802803    @property804    def cookies(self) -> "Cookies":805        if not hasattr(self, "_cookies"):806            assert self.request is not None807            self._cookies = Cookies()808            self._cookies.extract_cookies(self)809        return self._cookies810811    def __repr__(self) -> str:812        return f"<Response [{self.status_code} {self.reason_phrase}])>"813814815class AsyncResponse(BaseResponse):816    def __init__(817        self,818        status_code: int,819        *,820        protocol: str = None,821        headers: HeaderTypes = None,822        content: AsyncResponseContent = None,823        on_close: typing.Callable = None,824        request: AsyncRequest = None,825        history: typing.List["BaseResponse"] = None,826    ):827        super().__init__(828            status_code=status_code,829            protocol=protocol,830            headers=headers,831            request=request,832            on_close=on_close,833        )834835        self.history = [] if history is None else list(history)836837        if content is None or isinstance(content, bytes):838            self.is_closed = True839            self.is_stream_consumed = True840            self._raw_content = content or b""841        else:842            self.is_closed = False843            self.is_stream_consumed = False844            self._raw_stream = content845846    async def read(self) -> bytes:847        """848        Read and return the response content.849        """850        if not hasattr(self, "_content"):851            self._content = b"".join([part async for part in self.stream()])852        return self._content853854    async def stream(self) -> typing.AsyncIterator[bytes]:855        """856        A byte-iterator over the decoded response content.857        This allows us to handle gzip, deflate, and brotli encoded responses.858        """859        if hasattr(self, "_content"):860            yield self._content861        else:862            async for chunk in self.raw():863                yield self.decoder.decode(chunk)864            yield self.decoder.flush()865866    async def raw(self) -> typing.AsyncIterator[bytes]:867        """868        A byte-iterator over the raw response content.869        """870        if hasattr(self, "_raw_content"):871            yield self._raw_content872        else:873            if self.is_stream_consumed:874                raise StreamConsumed()875            if self.is_closed:876                raise ResponseClosed()877878            self.is_stream_consumed = True879            async for part in self._raw_stream:880                yield part881            await self.close()882883    async def close(self) -> None:884        """885        Close the response and release the connection.886        Automatically called if the response body is read to completion.887        """888        if not self.is_closed:889            self.is_closed = True890            if self.on_close is not None:891                await self.on_close()892893894class Response(BaseResponse):895    def __init__(896        self,897        status_code: int,898        *,899        protocol: str = None,900        headers: HeaderTypes = None,901        content: ResponseContent = None,902        on_close: typing.Callable = None,903        request: Request = None,904        history: typing.List["BaseResponse"] = None,905    ):906        super().__init__(907            status_code=status_code,908            protocol=protocol,909            headers=headers,910            request=request,911            on_close=on_close,912        )913914        self.history = [] if history is None else list(history)915916        if content is None or isinstance(content, bytes):917            self.is_closed = True918            self.is_stream_consumed = True919            self._raw_content = content or b""920        else:921            self.is_closed = False922            self.is_stream_consumed = False923            self._raw_stream = content924925    def read(self) -> bytes:926        """927        Read and return the response content.928        """929        if not hasattr(self, "_content"):930            self._content = b"".join([part for part in self.stream()])931        return self._content932933    def stream(self) -> typing.Iterator[bytes]:934        """935        A byte-iterator over the decoded response content.936        This allows us to handle gzip, deflate, and brotli encoded responses.937        """938        if hasattr(self, "_content"):939            yield self._content940        else:941            for chunk in self.raw():942                yield self.decoder.decode(chunk)943            yield self.decoder.flush()944945    def raw(self) -> typing.Iterator[bytes]:946        """947        A byte-iterator over the raw response content.948        """949        if hasattr(self, "_raw_content"):950            yield self._raw_content951        else:952            if self.is_stream_consumed:953                raise StreamConsumed()954            if self.is_closed:955                raise ResponseClosed()956957            self.is_stream_consumed = True958            for part in self._raw_stream:959                yield part960            self.close()961962    def close(self) -> None:963        """964        Close the response and release the connection.965        Automatically called if the response body is read to completion.966        """967        if not self.is_closed:968            self.is_closed = True969            if self.on_close is not None:970                self.on_close()971972973class Cookies(MutableMapping):974    """975    HTTP Cookies, as a mutable mapping.976    """977978    def __init__(self, cookies: CookieTypes = None) -> None:979        if cookies is None or isinstance(cookies, dict):980            self.jar = CookieJar()981            if isinstance(cookies, dict):982                for key, value in cookies.items():983                    self.set(key, value)984        elif isinstance(cookies, Cookies):985            self.jar = CookieJar()986            for cookie in cookies.jar:987                self.jar.set_cookie(cookie)988        else:989            self.jar = cookies990991    def extract_cookies(self, response: BaseResponse) -> None:992        """993        Loads any cookies based on the response `Set-Cookie` headers.994        """995        assert response.request is not None996        urlib_response = self._CookieCompatResponse(response)997        urllib_request = self._CookieCompatRequest(response.request)998999        self.jar.extract_cookies(urlib_response, urllib_request)  # type: ignore10001001    def set_cookie_header(self, request: BaseRequest) -> None:1002        """1003        Sets an appropriate 'Cookie:' HTTP header on the `Request`.1004        """1005        urllib_request = self._CookieCompatRequest(request)1006        self.jar.add_cookie_header(urllib_request)10071008    def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:1009        """1010        Set a cookie value by name. May optionally include domain and path.1011        """1012        kwargs = dict(1013            version=0,1014            name=name,1015            value=value,1016            port=None,1017            port_specified=False,1018            domain=domain,1019            domain_specified=bool(domain),1020            domain_initial_dot=domain.startswith("."),1021            path=path,1022            path_specified=bool(path),1023            secure=False,1024            expires=None,1025            discard=True,1026            comment=None,1027            comment_url=None,1028            rest={"HttpOnly": None},1029            rfc2109=False,1030        )1031        cookie = Cookie(**kwargs)  # type: ignore1032        self.jar.set_cookie(cookie)10331034    def get(  # type: ignore1035        self, name: str, default: str = None, domain: str = None, path: str = None1036    ) -> typing.Optional[str]:1037        """1038        Get a cookie by name. May optionally include domain and path1039        in order to specify exactly which cookie to retrieve.1040        """1041        value = None1042        for cookie in self.jar:1043            if cookie.name == name:1044                if domain is None or cookie.domain == domain:  # type: ignore1045                    if path is None or cookie.path == path:1046                        if value is not None:1047                            message = f"Multiple cookies exist with name={name}"1048                            raise CookieConflict(message)1049                        value = cookie.value10501051        if value is None:1052            return default1053        return value10541055    def delete(self, name: str, domain: str = None, path: str = None) -> None:1056        """1057        Delete a cookie by name. May optionally include domain and path1058        in order to specify exactly which cookie to delete.1059        """1060        if domain is not None and path is not None:1061            return self.jar.clear(domain, path, name)10621063        remove = []1064        for cookie in self.jar:1065            if cookie.name == name:1066                if domain is None or cookie.domain == domain:  # type: ignore1067                    if path is None or cookie.path == path:1068                        remove.append(cookie)10691070        for cookie in remove:1071            self.jar.clear(cookie.domain, cookie.path, cookie.name)  # type: ignore10721073    def clear(self, domain: str = None, path: str = None) -> None:1074        """1075        Delete all cookies. Optionally include a domain and path in1076        order to only delete a subset of all the cookies.1077        """1078        args = []1079        if domain is not None:1080            args.append(domain)1081        if path is not None:1082            assert domain is not None1083            args.append(path)1084        self.jar.clear(*args)10851086    def update(self, cookies: CookieTypes = None) -> None:  # type: ignore1087        cookies = Cookies(cookies)1088        for cookie in cookies.jar:1089            self.jar.set_cookie(cookie)10901091    def __setitem__(self, name: str, value: str) -> None:1092        return self.set(name, value)10931094    def __getitem__(self, name: str) -> str:1095        value = self.get(name)1096        if value is None:1097            raise KeyError(name)1098        return value10991100    def __delitem__(self, name: str) -> None:1101        return self.delete(name)11021103    def __len__(self) -> int:1104        return len(self.jar)11051106    def __iter__(self) -> typing.Iterator[str]:1107        return (cookie.name for cookie in self.jar)11081109    def __bool__(self) -> bool:1110        for cookie in self.jar:1111            return True1112        return False11131114    class _CookieCompatRequest(urllib.request.Request):1115        """1116        Wraps a `Request` instance up in a compatability interface suitable1117        for use with `CookieJar` operations.1118        """11191120        def __init__(self, request: BaseRequest) -> None:1121            super().__init__(1122                url=str(request.url),1123                headers=dict(request.headers),1124                method=request.method,1125            )1126            self.request = request11271128        def add_unredirected_header(self, key: str, value: str) -> None:1129            super().add_unredirected_header(key, value)1130            self.request.headers[key] = value11311132    class _CookieCompatResponse:1133        """1134        Wraps a `Request` instance up in a compatability interface suitable1135        for use with `CookieJar` operations.1136        """11371138        def __init__(self, response: BaseResponse):1139            self.response = response11401141        def info(self) -> email.message.Message:1142            info = email.message.Message()1143            for key, value in self.response.headers.items():1144                info[key] = value1145            return info