Skip to content
Myr

models.py

This file

Path

http3/models.py

1,127 lines · 35.2 KiB · Python

Last changed by

http3 (#86)Tom Christiebefore adoptionc9747aa

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 .status_codes import StatusCode29from .utils import is_known_encoding, normalize_header_key, normalize_header_value3031URLTypes = typing.Union["URL", str]3233QueryParamTypes = typing.Union[34    "QueryParams",35    typing.Mapping[str, str],36    typing.List[typing.Tuple[typing.Any, typing.Any]],37    str,38]3940HeaderTypes = typing.Union[41    "Headers",42    typing.Dict[typing.AnyStr, typing.AnyStr],43    typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],44]4546CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]4748AuthTypes = typing.Union[49    typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],50    typing.Callable[["AsyncRequest"], "AsyncRequest"],51]5253AsyncRequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]5455RequestData = typing.Union[dict, bytes, typing.Iterator[bytes]]5657AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]5859ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]606162class URL:63    def __init__(64        self,65        url: URLTypes,66        allow_relative: bool = False,67        params: QueryParamTypes = None,68    ) -> None:69        if isinstance(url, rfc3986.uri.URIReference):70            self.components = url71        elif isinstance(url, str):72            self.components = rfc3986.api.uri_reference(url)73        else:74            self.components = url.components7576        # Handle IDNA domain names.77        if self.components.authority:78            idna_authority = self.components.authority.encode("idna").decode("ascii")79            if idna_authority != self.components.authority:80                self.components = self.components.copy_with(authority=idna_authority)8182        # Normalize scheme and domain name.83        self.components = self.components.normalize()8485        # Add any query parameters.86        if params:87            query_string = str(QueryParams(params))88            self.components = self.components.copy_with(query=query_string)8990        # Enforce absolute URLs by default.91        if not allow_relative:92            if not self.scheme:93                raise InvalidURL("No scheme included in URL.")94            if self.scheme not in ("http", "https"):95                raise InvalidURL('URL scheme must be "http" or "https".')96            if not self.host:97                raise InvalidURL("No host included in URL.")9899    @property100    def scheme(self) -> str:101        return self.components.scheme or ""102103    @property104    def authority(self) -> str:105        return self.components.authority or ""106107    @property108    def username(self) -> str:109        userinfo = self.components.userinfo or ""110        return userinfo.partition(":")[0]111112    @property113    def password(self) -> str:114        userinfo = self.components.userinfo or ""115        return userinfo.partition(":")[2]116117    @property118    def host(self) -> str:119        return self.components.host or ""120121    @property122    def port(self) -> int:123        port = self.components.port124        if port is None:125            return {"https": 443, "http": 80}[self.scheme]126        return int(port)127128    @property129    def path(self) -> str:130        return self.components.path or "/"131132    @property133    def query(self) -> str:134        return self.components.query or ""135136    @property137    def full_path(self) -> str:138        path = self.path139        if self.query:140            path += "?" + self.query141        return path142143    @property144    def fragment(self) -> str:145        return self.components.fragment or ""146147    @property148    def is_ssl(self) -> bool:149        return self.components.scheme == "https"150151    @property152    def is_absolute_url(self) -> bool:153        """154        Return `True` for absolute URLs such as 'http://example.com/path',155        and `False` for relative URLs such as '/path'.156        """157        # We don't use rfc3986's `is_absolute` because it treats158        # URLs with a fragment portion as not absolute.159        # What we actually care about is if the URL provides160        # a scheme and hostname to which connections should be made.161        return self.components.scheme and self.components.host162163    @property164    def is_relative_url(self) -> bool:165        return not self.is_absolute_url166167    @property168    def origin(self) -> "Origin":169        return Origin(self)170171    def copy_with(self, **kwargs: typing.Any) -> "URL":172        return URL(self.components.copy_with(**kwargs))173174    def resolve_with(self, base_url: URLTypes) -> "URL":175        """176        Return an absolute URL, using base_url as the base.177        """178        # We drop any fragment portion, because RFC 3986 strictly179        # treats URLs with a fragment portion as not being absolute URLs.180        base_url = URL(base_url).copy_with(fragment=None)181        return URL(self.components.resolve_with(base_url.components))182183    def __hash__(self) -> int:184        return hash(str(self))185186    def __eq__(self, other: typing.Any) -> bool:187        return isinstance(other, URL) and str(self) == str(other)188189    def __str__(self) -> str:190        return self.components.unsplit()191192    def __repr__(self) -> str:193        class_name = self.__class__.__name__194        url_str = str(self)195        return f"{class_name}({url_str!r})"196197198class Origin:199    """200    The URL scheme and authority information, as a comparable, hashable object.201    """202203    def __init__(self, url: URLTypes) -> None:204        if not isinstance(url, URL):205            url = URL(url)206        self.is_ssl = url.is_ssl207        self.host = url.host208        self.port = url.port209210    def __eq__(self, other: typing.Any) -> bool:211        return (212            isinstance(other, self.__class__)213            and self.is_ssl == other.is_ssl214            and self.host == other.host215            and self.port == other.port216        )217218    def __hash__(self) -> int:219        return hash((self.is_ssl, self.host, self.port))220221222class QueryParams(typing.Mapping[str, str]):223    """224    URL query parameters, as a multi-dict.225    """226227    def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:228        assert len(args) < 2, "Too many arguments."229        assert not (args and kwargs), "Cannot mix named and unnamed arguments."230231        value = args[0] if args else kwargs232233        if isinstance(value, str):234            items = parse_qsl(value)235        elif isinstance(value, QueryParams):236            items = value.multi_items()237        elif isinstance(value, list):238            items = value239        else:240            items = value.items()  # type: ignore241242        self._list = [(str(k), str(v)) for k, v in items]243        self._dict = {str(k): str(v) for k, v in items}244245    def getlist(self, key: typing.Any) -> typing.List[str]:246        return [item_value for item_key, item_value in self._list if item_key == key]247248    def keys(self) -> typing.KeysView:249        return self._dict.keys()250251    def values(self) -> typing.ValuesView:252        return self._dict.values()253254    def items(self) -> typing.ItemsView:255        return self._dict.items()256257    def multi_items(self) -> typing.List[typing.Tuple[str, str]]:258        return list(self._list)259260    def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:261        if key in self._dict:262            return self._dict[key]263        return default264265    def __getitem__(self, key: typing.Any) -> str:266        return self._dict[key]267268    def __contains__(self, key: typing.Any) -> bool:269        return key in self._dict270271    def __iter__(self) -> typing.Iterator[typing.Any]:272        return iter(self.keys())273274    def __len__(self) -> int:275        return len(self._dict)276277    def __eq__(self, other: typing.Any) -> bool:278        if not isinstance(other, self.__class__):279            return False280        return sorted(self._list) == sorted(other._list)281282    def __str__(self) -> str:283        return urlencode(self._list)284285    def __repr__(self) -> str:286        class_name = self.__class__.__name__287        query_string = str(self)288        return f"{class_name}({query_string!r})"289290291class Headers(typing.MutableMapping[str, str]):292    """293    HTTP headers, as a case-insensitive multi-dict.294    """295296    def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:297        if headers is None:298            self._list = []  # type: typing.List[typing.Tuple[bytes, bytes]]299        elif isinstance(headers, Headers):300            self._list = list(headers.raw)301        elif isinstance(headers, dict):302            self._list = [303                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))304                for k, v in headers.items()305            ]306        else:307            self._list = [308                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))309                for k, v in headers310            ]311        self._encoding = encoding312313    @property314    def encoding(self) -> str:315        """316        Header encoding is mandated as ascii, but we allow fallbacks to utf-8317        or iso-8859-1.318        """319        if self._encoding is None:320            for encoding in ["ascii", "utf-8"]:321                for key, value in self.raw:322                    try:323                        key.decode(encoding)324                        value.decode(encoding)325                    except UnicodeDecodeError:326                        break327                else:328                    # The else block runs if 'break' did not occur, meaning329                    # all values fitted the encoding.330                    self._encoding = encoding331                    break332            else:333                # The ISO-8859-1 encoding covers all 256 code points in a byte,334                # so will never raise decode errors.335                self._encoding = "iso-8859-1"336        return self._encoding337338    @encoding.setter339    def encoding(self, value: str) -> None:340        self._encoding = value341342    @property343    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:344        """345        Returns a list of the raw header items, as byte pairs.346        May be mutated in-place.347        """348        return self._list349350    def keys(self) -> typing.List[str]:  # type: ignore351        return [key.decode(self.encoding) for key, value in self._list]352353    def values(self) -> typing.List[str]:  # type: ignore354        return [value.decode(self.encoding) for key, value in self._list]355356    def items(self) -> typing.List[typing.Tuple[str, str]]:  # type: ignore357        return [358            (key.decode(self.encoding), value.decode(self.encoding))359            for key, value in self._list360        ]361362    def get(self, key: str, default: typing.Any = None) -> typing.Any:363        try:364            return self[key]365        except KeyError:366            return default367368    def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:369        """370        Return multiple header values.371        """372        get_header_key = key.lower().encode(self.encoding)373374        values = [375            item_value.decode(self.encoding)376            for item_key, item_value in self._list377            if item_key == get_header_key378        ]379380        if not split_commas:381            return values382383        split_values = []384        for value in values:385            split_values.extend([item.strip() for item in value.split(",")])386        return split_values387388    def __getitem__(self, key: str) -> str:389        """390        Return a single header value.391392        If there are multiple headers with the same key, then we concatenate393        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2394        """395        normalized_key = key.lower().encode(self.encoding)396397        items = []398        for header_key, header_value in self._list:399            if header_key == normalized_key:400                items.append(header_value.decode(self.encoding))401402        if items:403            return ", ".join(items)404405        raise KeyError(key)406407    def __setitem__(self, key: str, value: str) -> None:408        """409        Set the header `key` to `value`, removing any duplicate entries.410        Retains insertion order.411        """412        set_key = key.lower().encode(self.encoding)413        set_value = value.encode(self.encoding)414415        found_indexes = []416        for idx, (item_key, item_value) in enumerate(self._list):417            if item_key == set_key:418                found_indexes.append(idx)419420        for idx in reversed(found_indexes[1:]):421            del self._list[idx]422423        if found_indexes:424            idx = found_indexes[0]425            self._list[idx] = (set_key, set_value)426        else:427            self._list.append((set_key, set_value))428429    def __delitem__(self, key: str) -> None:430        """431        Remove the header `key`.432        """433        del_key = key.lower().encode(self.encoding)434435        pop_indexes = []436        for idx, (item_key, item_value) in enumerate(self._list):437            if item_key == del_key:438                pop_indexes.append(idx)439440        for idx in reversed(pop_indexes):441            del self._list[idx]442443    def __contains__(self, key: typing.Any) -> bool:444        get_header_key = key.lower().encode(self.encoding)445        for header_key, header_value in self._list:446            if header_key == get_header_key:447                return True448        return False449450    def __iter__(self) -> typing.Iterator[typing.Any]:451        return iter(self.keys())452453    def __len__(self) -> int:454        return len(self._list)455456    def __eq__(self, other: typing.Any) -> bool:457        if not isinstance(other, Headers):458            return False459        return sorted(self._list) == sorted(other._list)460461    def __repr__(self) -> str:462        class_name = self.__class__.__name__463464        encoding_str = ""465        if self.encoding != "ascii":466            encoding_str = f", encoding={self.encoding!r}"467468        as_dict = dict(self.items())469        if len(as_dict) == len(self):470            return f"{class_name}({as_dict!r}{encoding_str})"471        as_list = self.items()472        return f"{class_name}({as_list!r}{encoding_str})"473474475class BaseRequest:476    def __init__(477        self,478        method: str,479        url: typing.Union[str, URL],480        *,481        params: QueryParamTypes = None,482        headers: HeaderTypes = None,483        cookies: CookieTypes = None,484    ):485        self.method = method.upper()486        self.url = URL(url, params=params)487        self.headers = Headers(headers)488        if cookies:489            self._cookies = Cookies(cookies)490            self._cookies.set_cookie_header(self)491492    def encode_json(self, json: typing.Any) -> bytes:493        return jsonlib.dumps(json).encode("utf-8")494495    def urlencode_data(self, data: dict) -> bytes:496        return urlencode(data, doseq=True).encode("utf-8")497498    def prepare(self) -> None:499        content = getattr(self, "content", None)  # type: bytes500        is_streaming = getattr(self, "is_streaming", False)501502        auto_headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]503504        has_user_agent = "user-agent" in self.headers505        has_accept = "accept" in self.headers506        has_content_length = (507            "content-length" in self.headers or "transfer-encoding" in self.headers508        )509        has_accept_encoding = "accept-encoding" in self.headers510511        if not has_user_agent:512            auto_headers.append((b"user-agent", b"http3"))513        if not has_accept:514            auto_headers.append((b"accept", b"*/*"))515        if not has_content_length:516            if is_streaming:517                auto_headers.append((b"transfer-encoding", b"chunked"))518            elif content:519                content_length = str(len(content)).encode()520                auto_headers.append((b"content-length", content_length))521        if not has_accept_encoding:522            auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))523524        for item in reversed(auto_headers):525            self.headers.raw.insert(0, item)526527    @property528    def cookies(self) -> "Cookies":529        if not hasattr(self, "_cookies"):530            self._cookies = Cookies()531        return self._cookies532533    def __repr__(self) -> str:534        class_name = self.__class__.__name__535        url = str(self.url)536        return f"<{class_name}({self.method!r}, {url!r})>"537538539class AsyncRequest(BaseRequest):540    def __init__(541        self,542        method: str,543        url: typing.Union[str, URL],544        *,545        params: QueryParamTypes = None,546        headers: HeaderTypes = None,547        cookies: CookieTypes = None,548        data: AsyncRequestData = b"",549        json: typing.Any = None,550    ):551        super().__init__(552            method=method, url=url, params=params, headers=headers, cookies=cookies553        )554555        if json is not None:556            self.is_streaming = False557            self.content = self.encode_json(json)558            self.headers["Content-Type"] = "application/json"559        elif isinstance(data, bytes):560            self.is_streaming = False561            self.content = data562        elif isinstance(data, dict):563            self.is_streaming = False564            self.content = self.urlencode_data(data)565            self.headers["Content-Type"] = "application/x-www-form-urlencoded"566        else:567            assert hasattr(data, "__aiter__")568            self.is_streaming = True569            self.content_aiter = data570571        self.prepare()572573    async def read(self) -> bytes:574        """575        Read and return the response content.576        """577        if not hasattr(self, "content"):578            self.content = b"".join([part async for part in self.stream()])579        return self.content580581    async def stream(self) -> typing.AsyncIterator[bytes]:582        if self.is_streaming:583            async for part in self.content_aiter:584                yield part585        elif self.content:586            yield self.content587588589class Request(BaseRequest):590    def __init__(591        self,592        method: str,593        url: typing.Union[str, URL],594        *,595        params: QueryParamTypes = None,596        headers: HeaderTypes = None,597        cookies: CookieTypes = None,598        data: RequestData = b"",599        json: typing.Any = None,600    ):601        super().__init__(602            method=method, url=url, params=params, headers=headers, cookies=cookies603        )604605        if json is not None:606            self.is_streaming = False607            self.content = self.encode_json(json)608            self.headers["Content-Type"] = "application/json"609        elif isinstance(data, bytes):610            self.is_streaming = False611            self.content = data612        elif isinstance(data, dict):613            self.is_streaming = False614            self.content = self.urlencode_data(data)615            self.headers["Content-Type"] = "application/x-www-form-urlencoded"616        else:617            assert hasattr(data, "__iter__")618            self.is_streaming = True619            self.content_iter = data620621        self.prepare()622623    def read(self) -> bytes:624        if not hasattr(self, "content"):625            self.content = b"".join([part for part in self.stream()])626        return self.content627628    def stream(self) -> typing.Iterator[bytes]:629        if self.is_streaming:630            for part in self.content_iter:631                yield part632        elif self.content:633            yield self.content634635636class BaseResponse:637    def __init__(638        self,639        status_code: int,640        *,641        reason_phrase: str = None,642        protocol: str = None,643        headers: HeaderTypes = None,644        request: BaseRequest = None,645        on_close: typing.Callable = None,646    ):647        self.status_code = StatusCode.enum_or_int(status_code)648        self.reason_phrase = StatusCode.get_reason_phrase(status_code)649        self.protocol = protocol650        self.headers = Headers(headers)651652        self.request = request653        self.on_close = on_close654        self.next = None  # typing.Optional[typing.Callable]655656    @property657    def url(self) -> typing.Optional[URL]:658        """659        Returns the URL for which the request was made.660661        Requires that `request` was provided when instantiating the response.662        """663        return None if self.request is None else self.request.url664665    @property666    def content(self) -> bytes:667        if not hasattr(self, "_content"):668            if hasattr(self, "_raw_content"):669                raw_content = getattr(self, "_raw_content")  # type: bytes670                content = self.decoder.decode(raw_content)671                content += self.decoder.flush()672                self._content = content673            else:674                raise ResponseNotRead()675        return self._content676677    @property678    def text(self) -> str:679        if not hasattr(self, "_text"):680            content = self.content681            if not content:682                self._text = ""683            else:684                encoding = self.encoding685                self._text = content.decode(encoding, errors="replace")686        return self._text687688    @property689    def encoding(self) -> str:690        if not hasattr(self, "_encoding"):691            encoding = self.charset_encoding692            if encoding is None or not is_known_encoding(encoding):693                encoding = self.apparent_encoding694                if encoding is None or not is_known_encoding(encoding):695                    encoding = "utf-8"696            self._encoding = encoding697        return self._encoding698699    @encoding.setter700    def encoding(self, value: str) -> None:701        self._encoding = value702703    @property704    def charset_encoding(self) -> typing.Optional[str]:705        """706        Return the encoding, as specified by the Content-Type header.707        """708        content_type = self.headers.get("Content-Type")709        if content_type is None:710            return None711712        parsed = cgi.parse_header(content_type)713        media_type, params = parsed[0], parsed[-1]714        if "charset" in params:715            return params["charset"].strip("'\"")716717        # RFC 2616 specifies that 'iso-8859-1' should be used as the default718        # for 'text/*' media types, if no charset is provided.719        # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1720        if media_type.startswith("text/"):721            return "iso-8859-1"722723        return None724725    @property726    def apparent_encoding(self) -> typing.Optional[str]:727        """728        Return the encoding, as it appears to autodetection.729        """730        return chardet.detect(self.content)["encoding"]731732    @property733    def decoder(self) -> Decoder:734        """735        Returns a decoder instance which can be used to decode the raw byte736        content, depending on the Content-Encoding used in the response.737        """738        if not hasattr(self, "_decoder"):739            decoders = []  # type: typing.List[Decoder]740            values = self.headers.getlist("content-encoding", split_commas=True)741            for value in values:742                value = value.strip().lower()743                decoder_cls = SUPPORTED_DECODERS[value]744                decoders.append(decoder_cls())745746            if len(decoders) == 1:747                self._decoder = decoders[0]748            elif len(decoders) > 1:749                self._decoder = MultiDecoder(decoders)750            else:751                self._decoder = IdentityDecoder()752753        return self._decoder754755    @property756    def is_redirect(self) -> bool:757        return StatusCode.is_redirect(self.status_code) and "location" in self.headers758759    def raise_for_status(self) -> None:760        """761        Raise the `HttpError` if one occurred.762        """763        message = (764            "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"765            "For more information check: https://httpstatuses.com/{0.status_code}"766        )767768        if StatusCode.is_client_error(self.status_code):769            message = message.format(self, error_type="Client Error")770        elif StatusCode.is_server_error(self.status_code):771            message = message.format(self, error_type="Server Error")772        else:773            message = ""774775        if message:776            raise HttpError(message)777778    def json(self) -> typing.Any:779        return jsonlib.loads(self.content.decode("utf-8"))780781    @property782    def cookies(self) -> "Cookies":783        if not hasattr(self, "_cookies"):784            assert self.request is not None785            self._cookies = Cookies()786            self._cookies.extract_cookies(self)787        return self._cookies788789    def __repr__(self) -> str:790        return f"<Response({self.status_code}, {self.reason_phrase!r})>"791792793class AsyncResponse(BaseResponse):794    def __init__(795        self,796        status_code: int,797        *,798        reason_phrase: str = None,799        protocol: str = None,800        headers: HeaderTypes = None,801        content: AsyncResponseContent = b"",802        on_close: typing.Callable = None,803        request: AsyncRequest = None,804        history: typing.List["BaseResponse"] = None,805    ):806        super().__init__(807            status_code=status_code,808            reason_phrase=reason_phrase,809            protocol=protocol,810            headers=headers,811            request=request,812            on_close=on_close,813        )814815        self.history = [] if history is None else list(history)816817        if isinstance(content, bytes):818            self.is_closed = True819            self.is_stream_consumed = True820            self._raw_content = content821        else:822            self.is_closed = False823            self.is_stream_consumed = False824            self._raw_stream = content825826    async def read(self) -> bytes:827        """828        Read and return the response content.829        """830        if not hasattr(self, "_content"):831            self._content = b"".join([part async for part in self.stream()])832        return self._content833834    async def stream(self) -> typing.AsyncIterator[bytes]:835        """836        A byte-iterator over the decoded response content.837        This allows us to handle gzip, deflate, and brotli encoded responses.838        """839        if hasattr(self, "_content"):840            yield self._content841        else:842            async for chunk in self.raw():843                yield self.decoder.decode(chunk)844            yield self.decoder.flush()845846    async def raw(self) -> typing.AsyncIterator[bytes]:847        """848        A byte-iterator over the raw response content.849        """850        if hasattr(self, "_raw_content"):851            yield self._raw_content852        else:853            if self.is_stream_consumed:854                raise StreamConsumed()855            if self.is_closed:856                raise ResponseClosed()857858            self.is_stream_consumed = True859            async for part in self._raw_stream:860                yield part861            await self.close()862863    async def close(self) -> None:864        """865        Close the response and release the connection.866        Automatically called if the response body is read to completion.867        """868        if not self.is_closed:869            self.is_closed = True870            if self.on_close is not None:871                await self.on_close()872873874class Response(BaseResponse):875    def __init__(876        self,877        status_code: int,878        *,879        reason_phrase: str = None,880        protocol: str = None,881        headers: HeaderTypes = None,882        content: ResponseContent = b"",883        on_close: typing.Callable = None,884        request: Request = None,885        history: typing.List["BaseResponse"] = None,886    ):887        super().__init__(888            status_code=status_code,889            reason_phrase=reason_phrase,890            protocol=protocol,891            headers=headers,892            request=request,893            on_close=on_close,894        )895896        self.history = [] if history is None else list(history)897898        if isinstance(content, bytes):899            self.is_closed = True900            self.is_stream_consumed = True901            self._raw_content = content902        else:903            self.is_closed = False904            self.is_stream_consumed = False905            self._raw_stream = content906907    def read(self) -> bytes:908        """909        Read and return the response content.910        """911        if not hasattr(self, "_content"):912            self._content = b"".join([part for part in self.stream()])913        return self._content914915    def stream(self) -> typing.Iterator[bytes]:916        """917        A byte-iterator over the decoded response content.918        This allows us to handle gzip, deflate, and brotli encoded responses.919        """920        if hasattr(self, "_content"):921            yield self._content922        else:923            for chunk in self.raw():924                yield self.decoder.decode(chunk)925            yield self.decoder.flush()926927    def raw(self) -> typing.Iterator[bytes]:928        """929        A byte-iterator over the raw response content.930        """931        if hasattr(self, "_raw_content"):932            yield self._raw_content933        else:934            if self.is_stream_consumed:935                raise StreamConsumed()936            if self.is_closed:937                raise ResponseClosed()938939            self.is_stream_consumed = True940            for part in self._raw_stream:941                yield part942            self.close()943944    def close(self) -> None:945        """946        Close the response and release the connection.947        Automatically called if the response body is read to completion.948        """949        if not self.is_closed:950            self.is_closed = True951            if self.on_close is not None:952                self.on_close()953954955class Cookies(MutableMapping):956    """957    HTTP Cookies, as a mutable mapping.958    """959960    def __init__(self, cookies: CookieTypes = None) -> None:961        if cookies is None or isinstance(cookies, dict):962            self.jar = CookieJar()963            if isinstance(cookies, dict):964                for key, value in cookies.items():965                    self.set(key, value)966        elif isinstance(cookies, Cookies):967            self.jar = CookieJar()968            for cookie in cookies.jar:969                self.jar.set_cookie(cookie)970        else:971            self.jar = cookies972973    def extract_cookies(self, response: BaseResponse) -> None:974        """975        Loads any cookies based on the response `Set-Cookie` headers.976        """977        assert response.request is not None978        urlib_response = self._CookieCompatResponse(response)979        urllib_request = self._CookieCompatRequest(response.request)980981        self.jar.extract_cookies(urlib_response, urllib_request)  # type: ignore982983    def set_cookie_header(self, request: BaseRequest) -> None:984        """985        Sets an appropriate 'Cookie:' HTTP header on the `Request`.986        """987        urllib_request = self._CookieCompatRequest(request)988        self.jar.add_cookie_header(urllib_request)989990    def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:991        """992        Set a cookie value by name. May optionally include domain and path.993        """994        kwargs = dict(995            version=0,996            name=name,997            value=value,998            port=None,999            port_specified=False,1000            domain=domain,1001            domain_specified=bool(domain),1002            domain_initial_dot=domain.startswith("."),1003            path=path,1004            path_specified=bool(path),1005            secure=False,1006            expires=None,1007            discard=True,1008            comment=None,1009            comment_url=None,1010            rest={"HttpOnly": None},1011            rfc2109=False,1012        )1013        cookie = Cookie(**kwargs)  # type: ignore1014        self.jar.set_cookie(cookie)10151016    def get(  # type: ignore1017        self, name: str, default: str = None, domain: str = None, path: str = None1018    ) -> typing.Optional[str]:1019        """1020        Get a cookie by name. May optionally include domain and path1021        in order to specify exactly which cookie to retrieve.1022        """1023        value = None1024        for cookie in self.jar:1025            if cookie.name == name:1026                if domain is None or cookie.domain == domain:  # type: ignore1027                    if path is None or cookie.path == path:1028                        if value is not None:1029                            message = f"Multiple cookies exist with name={name}"1030                            raise CookieConflict(message)1031                        value = cookie.value10321033        if value is None:1034            return default1035        return value10361037    def delete(self, name: str, domain: str = None, path: str = None) -> None:1038        """1039        Delete a cookie by name. May optionally include domain and path1040        in order to specify exactly which cookie to delete.1041        """1042        if domain is not None and path is not None:1043            return self.jar.clear(domain, path, name)10441045        remove = []1046        for cookie in self.jar:1047            if cookie.name == name:1048                if domain is None or cookie.domain == domain:  # type: ignore1049                    if path is None or cookie.path == path:1050                        remove.append(cookie)10511052        for cookie in remove:1053            self.jar.clear(cookie.domain, cookie.path, cookie.name)  # type: ignore10541055    def clear(self, domain: str = None, path: str = None) -> None:1056        """1057        Delete all cookies. Optionally include a domain and path in1058        order to only delete a subset of all the cookies.1059        """1060        args = []1061        if domain is not None:1062            args.append(domain)1063        if path is not None:1064            assert domain is not None1065            args.append(path)1066        self.jar.clear(*args)10671068    def update(self, cookies: CookieTypes = None) -> None:  # type: ignore1069        cookies = Cookies(cookies)1070        for cookie in cookies.jar:1071            self.jar.set_cookie(cookie)10721073    def __setitem__(self, name: str, value: str) -> None:1074        return self.set(name, value)10751076    def __getitem__(self, name: str) -> str:1077        value = self.get(name)1078        if value is None:1079            raise KeyError(name)1080        return value10811082    def __delitem__(self, name: str) -> None:1083        return self.delete(name)10841085    def __len__(self) -> int:1086        return len(self.jar)10871088    def __iter__(self) -> typing.Iterator[str]:1089        return (cookie.name for cookie in self.jar)10901091    def __bool__(self) -> bool:1092        for cookie in self.jar:1093            return True1094        return False10951096    class _CookieCompatRequest(urllib.request.Request):1097        """1098        Wraps a `Request` instance up in a compatability interface suitable1099        for use with `CookieJar` operations.1100        """11011102        def __init__(self, request: BaseRequest) -> None:1103            super().__init__(1104                url=str(request.url),1105                headers=dict(request.headers),1106                method=request.method,1107            )1108            self.request = request11091110        def add_unredirected_header(self, key: str, value: str) -> None:1111            super().add_unredirected_header(key, value)1112            self.request.headers[key] = value11131114    class _CookieCompatResponse:1115        """1116        Wraps a `Request` instance up in a compatability interface suitable1117        for use with `CookieJar` operations.1118        """11191120        def __init__(self, response: BaseResponse):1121            self.response = response11221123        def info(self) -> email.message.Message:1124            info = email.message.Message()1125            for key, value in self.response.headers.items():1126                info[key] = value1127            return info