Skip to content
Myr

models.py

This file

Path

httpcore/models.py

1,043 lines · 32.3 KiB · Python

Last changed by

query_params -> paramsTom Christiebefore adoptionbb70377

History of this file

Take it

1import asyncio2import cgi3import email.message4import 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 codes29from .utils import (30    get_reason_phrase,31    is_known_encoding,32    normalize_header_key,33    normalize_header_value,34)3536URLTypes = typing.Union["URL", str]3738QueryParamTypes = typing.Union[39    "QueryParams",40    typing.Mapping[str, str],41    typing.List[typing.Tuple[typing.Any, typing.Any]],42    str,43]4445HeaderTypes = typing.Union[46    "Headers",47    typing.Dict[typing.AnyStr, typing.AnyStr],48    typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],49]5051CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]5253AuthTypes = typing.Union[54    typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],55    typing.Callable[["Request"], "Request"],56]5758RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]5960ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]616263class URL:64    def __init__(65        self,66        url: URLTypes,67        allow_relative: bool = False,68        params: QueryParamTypes = None,69    ) -> None:70        if isinstance(url, rfc3986.uri.URIReference):71            self.components = url72        elif isinstance(url, str):73            self.components = rfc3986.api.uri_reference(url)74        else:75            self.components = url.components7677        # Handle IDNA domain names.78        if self.components.authority:79            idna_authority = self.components.authority.encode("idna").decode("ascii")80            if idna_authority != self.components.authority:81                self.components = self.components.copy_with(authority=idna_authority)8283        # Normalize scheme and domain name.84        self.components = self.components.normalize()8586        # Add any query parameters.87        if params:88            query_string = str(QueryParams(params))89            self.components = self.components.copy_with(query=query_string)9091        # Enforce absolute URLs by default.92        if not allow_relative:93            if not self.scheme:94                raise InvalidURL("No scheme included in URL.")95            if self.scheme not in ("http", "https"):96                raise InvalidURL('URL scheme must be "http" or "https".')97            if not self.host:98                raise InvalidURL("No host included in URL.")99100    @property101    def scheme(self) -> str:102        return self.components.scheme or ""103104    @property105    def authority(self) -> str:106        return self.components.authority or ""107108    @property109    def username(self) -> str:110        userinfo = self.components.userinfo or ""111        return userinfo.partition(":")[0]112113    @property114    def password(self) -> str:115        userinfo = self.components.userinfo or ""116        return userinfo.partition(":")[2]117118    @property119    def host(self) -> str:120        return self.components.host or ""121122    @property123    def port(self) -> int:124        port = self.components.port125        if port is None:126            return {"https": 443, "http": 80}[self.scheme]127        return int(port)128129    @property130    def path(self) -> str:131        return self.components.path or "/"132133    @property134    def query(self) -> str:135        return self.components.query or ""136137    @property138    def full_path(self) -> str:139        path = self.path140        if self.query:141            path += "?" + self.query142        return path143144    @property145    def fragment(self) -> str:146        return self.components.fragment or ""147148    @property149    def is_ssl(self) -> bool:150        return self.components.scheme == "https"151152    @property153    def is_absolute_url(self) -> bool:154        """155        Return `True` for absolute URLs such as 'http://example.com/path',156        and `False` for relative URLs such as '/path'.157        """158        # We don't use rfc3986's `is_absolute` because it treats159        # URLs with a fragment portion as not absolute.160        # What we actually care about is if the URL provides161        # a scheme and hostname to which connections should be made.162        return self.components.scheme and self.components.host163164    @property165    def is_relative_url(self) -> bool:166        return not self.is_absolute_url167168    @property169    def origin(self) -> "Origin":170        return Origin(self)171172    def copy_with(self, **kwargs: typing.Any) -> "URL":173        return URL(self.components.copy_with(**kwargs))174175    def resolve_with(self, base_url: URLTypes) -> "URL":176        """177        Return an absolute URL, using base_url as the base.178        """179        # We drop any fragment portion, because RFC 3986 strictly180        # treats URLs with a fragment portion as not being absolute URLs.181        base_url = URL(base_url).copy_with(fragment=None)182        return URL(self.components.resolve_with(base_url.components))183184    def __hash__(self) -> int:185        return hash(str(self))186187    def __eq__(self, other: typing.Any) -> bool:188        return isinstance(other, URL) and str(self) == str(other)189190    def __str__(self) -> str:191        return self.components.unsplit()192193    def __repr__(self) -> str:194        class_name = self.__class__.__name__195        url_str = str(self)196        return f"{class_name}({url_str!r})"197198199class Origin:200    """201    The URL scheme and authority information, as a comparable, hashable object.202    """203204    def __init__(self, url: URLTypes) -> None:205        if not isinstance(url, URL):206            url = URL(url)207        self.is_ssl = url.is_ssl208        self.host = url.host209        self.port = url.port210211    def __eq__(self, other: typing.Any) -> bool:212        return (213            isinstance(other, self.__class__)214            and self.is_ssl == other.is_ssl215            and self.host == other.host216            and self.port == other.port217        )218219    def __hash__(self) -> int:220        return hash((self.is_ssl, self.host, self.port))221222223class QueryParams(typing.Mapping[str, str]):224    """225    URL query parameters, as a multi-dict.226    """227228    def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:229        assert len(args) < 2, "Too many arguments."230        assert not (args and kwargs), "Cannot mix named and unnamed arguments."231232        value = args[0] if args else kwargs233234        if isinstance(value, str):235            items = parse_qsl(value)236        elif isinstance(value, QueryParams):237            items = value.multi_items()238        elif isinstance(value, list):239            items = value240        else:241            items = value.items()  # type: ignore242243        self._list = [(str(k), str(v)) for k, v in items]244        self._dict = {str(k): str(v) for k, v in items}245246    def getlist(self, key: typing.Any) -> typing.List[str]:247        return [item_value for item_key, item_value in self._list if item_key == key]248249    def keys(self) -> typing.KeysView:250        return self._dict.keys()251252    def values(self) -> typing.ValuesView:253        return self._dict.values()254255    def items(self) -> typing.ItemsView:256        return self._dict.items()257258    def multi_items(self) -> typing.List[typing.Tuple[str, str]]:259        return list(self._list)260261    def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:262        if key in self._dict:263            return self._dict[key]264        return default265266    def __getitem__(self, key: typing.Any) -> str:267        return self._dict[key]268269    def __contains__(self, key: typing.Any) -> bool:270        return key in self._dict271272    def __iter__(self) -> typing.Iterator[typing.Any]:273        return iter(self.keys())274275    def __len__(self) -> int:276        return len(self._dict)277278    def __eq__(self, other: typing.Any) -> bool:279        if not isinstance(other, self.__class__):280            return False281        return sorted(self._list) == sorted(other._list)282283    def __str__(self) -> str:284        return urlencode(self._list)285286    def __repr__(self) -> str:287        class_name = self.__class__.__name__288        query_string = str(self)289        return f"{class_name}({query_string!r})"290291292class Headers(typing.MutableMapping[str, str]):293    """294    HTTP headers, as a case-insensitive multi-dict.295    """296297    def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:298        if headers is None:299            self._list = []  # type: typing.List[typing.Tuple[bytes, bytes]]300        elif isinstance(headers, Headers):301            self._list = list(headers.raw)302        elif isinstance(headers, dict):303            self._list = [304                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))305                for k, v in headers.items()306            ]307        else:308            self._list = [309                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))310                for k, v in headers311            ]312        self._encoding = encoding313314    @property315    def encoding(self) -> str:316        """317        Header encoding is mandated as ascii, but we allow fallbacks to utf-8318        or iso-8859-1.319        """320        if self._encoding is None:321            for encoding in ["ascii", "utf-8"]:322                for key, value in self.raw:323                    try:324                        key.decode(encoding)325                        value.decode(encoding)326                    except UnicodeDecodeError:327                        break328                else:329                    # The else block runs if 'break' did not occur, meaning330                    # all values fitted the encoding.331                    self._encoding = encoding332                    break333            else:334                # The ISO-8859-1 encoding covers all 256 code points in a byte,335                # so will never raise decode errors.336                self._encoding = "iso-8859-1"337        return self._encoding338339    @encoding.setter340    def encoding(self, value: str) -> None:341        self._encoding = value342343    @property344    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:345        """346        Returns a list of the raw header items, as byte pairs.347        May be mutated in-place.348        """349        return self._list350351    def keys(self) -> typing.List[str]:  # type: ignore352        return [key.decode(self.encoding) for key, value in self._list]353354    def values(self) -> typing.List[str]:  # type: ignore355        return [value.decode(self.encoding) for key, value in self._list]356357    def items(self) -> typing.List[typing.Tuple[str, str]]:  # type: ignore358        return [359            (key.decode(self.encoding), value.decode(self.encoding))360            for key, value in self._list361        ]362363    def get(self, key: str, default: typing.Any = None) -> typing.Any:364        try:365            return self[key]366        except KeyError:367            return default368369    def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:370        """371        Return multiple header values.372        """373        get_header_key = key.lower().encode(self.encoding)374375        values = [376            item_value.decode(self.encoding)377            for item_key, item_value in self._list378            if item_key == get_header_key379        ]380381        if not split_commas:382            return values383384        split_values = []385        for value in values:386            split_values.extend([item.strip() for item in value.split(",")])387        return split_values388389    def __getitem__(self, key: str) -> str:390        """391        Return a single header value.392393        If there are multiple headers with the same key, then we concatenate394        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2395        """396        normalized_key = key.lower().encode(self.encoding)397398        items = []399        for header_key, header_value in self._list:400            if header_key == normalized_key:401                items.append(header_value.decode(self.encoding))402403        if items:404            return ", ".join(items)405406        raise KeyError(key)407408    def __setitem__(self, key: str, value: str) -> None:409        """410        Set the header `key` to `value`, removing any duplicate entries.411        Retains insertion order.412        """413        set_key = key.lower().encode(self.encoding)414        set_value = value.encode(self.encoding)415416        found_indexes = []417        for idx, (item_key, item_value) in enumerate(self._list):418            if item_key == set_key:419                found_indexes.append(idx)420421        for idx in reversed(found_indexes[1:]):422            del self._list[idx]423424        if found_indexes:425            idx = found_indexes[0]426            self._list[idx] = (set_key, set_value)427        else:428            self._list.append((set_key, set_value))429430    def __delitem__(self, key: str) -> None:431        """432        Remove the header `key`.433        """434        del_key = key.lower().encode(self.encoding)435436        pop_indexes = []437        for idx, (item_key, item_value) in enumerate(self._list):438            if item_key == del_key:439                pop_indexes.append(idx)440441        for idx in reversed(pop_indexes):442            del self._list[idx]443444    def __contains__(self, key: typing.Any) -> bool:445        get_header_key = key.lower().encode(self.encoding)446        for header_key, header_value in self._list:447            if header_key == get_header_key:448                return True449        return False450451    def __iter__(self) -> typing.Iterator[typing.Any]:452        return iter(self.keys())453454    def __len__(self) -> int:455        return len(self._list)456457    def __eq__(self, other: typing.Any) -> bool:458        if not isinstance(other, Headers):459            return False460        return sorted(self._list) == sorted(other._list)461462    def __repr__(self) -> str:463        class_name = self.__class__.__name__464465        encoding_str = ""466        if self.encoding != "ascii":467            encoding_str = f", encoding={self.encoding!r}"468469        as_dict = dict(self.items())470        if len(as_dict) == len(self):471            return f"{class_name}({as_dict!r}{encoding_str})"472        as_list = self.items()473        return f"{class_name}({as_list!r}{encoding_str})"474475476class Request:477    def __init__(478        self,479        method: str,480        url: typing.Union[str, URL],481        *,482        data: RequestData = b"",483        params: QueryParamTypes = None,484        headers: HeaderTypes = None,485        cookies: CookieTypes = None,486    ):487        self.method = method.upper()488        self.url = URL(url, params=params)489        self.headers = Headers(headers)490        if cookies:491            self._cookies = Cookies(cookies)492            self._cookies.set_cookie_header(self)493494        if isinstance(data, bytes):495            self.is_streaming = False496            self.content = data497        elif isinstance(data, dict):498            self.is_streaming = False499            self.content = urlencode(data, doseq=True).encode("utf-8")500            self.headers["Content-Type"] = "application/x-www-form-urlencoded"501        else:502            self.is_streaming = True503            self.content_aiter = data504505    async def read(self) -> bytes:506        """507        Read and return the response content.508        """509        if not hasattr(self, "content"):510            self.content = b"".join([part async for part in self.stream()])511        return self.content512513    async def stream(self) -> typing.AsyncIterator[bytes]:514        if self.is_streaming:515            async for part in self.content_aiter:516                yield part517        elif self.content:518            yield self.content519520    def prepare(self) -> None:521        """522        Adds in any default headers. When using the `Client`, this will523        end up being called into by the `prepare_request()` stage.524525        You can omit this behavior by calling `Client.send()` with an526        explicitly built `Request` instance.527        """528        auto_headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]529530        has_host = "host" in self.headers531        has_content_length = (532            "content-length" in self.headers or "transfer-encoding" in self.headers533        )534        has_accept_encoding = "accept-encoding" in self.headers535536        if not has_host and self.url.authority:537            auto_headers.append((b"host", self.url.authority.encode("ascii")))538        if not has_content_length:539            if self.is_streaming:540                auto_headers.append((b"transfer-encoding", b"chunked"))541            elif self.content:542                content_length = str(len(self.content)).encode()543                auto_headers.append((b"content-length", content_length))544        if not has_accept_encoding:545            auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))546547        for item in reversed(auto_headers):548            self.headers.raw.insert(0, item)549550    @property551    def cookies(self) -> "Cookies":552        if not hasattr(self, "_cookies"):553            self._cookies = Cookies()554        return self._cookies555556    def __repr__(self) -> str:557        class_name = self.__class__.__name__558        url = str(self.url)559        return f"<{class_name}({self.method!r}, {url!r})>"560561562class Response:563    def __init__(564        self,565        status_code: int,566        *,567        reason_phrase: str = None,568        protocol: str = None,569        headers: HeaderTypes = None,570        content: ResponseContent = b"",571        on_close: typing.Callable = None,572        request: Request = None,573        history: typing.List["Response"] = None,574    ):575        try:576            # Use a StatusCode IntEnum if possible, for a nicer representation.577            self.status_code = codes(status_code)  # type: int578        except ValueError:579            self.status_code = status_code580        self.reason_phrase = reason_phrase or get_reason_phrase(status_code)581        self.protocol = protocol582        self.headers = Headers(headers)583584        if isinstance(content, bytes):585            self.is_closed = True586            self.is_stream_consumed = True587            self._raw_content = content588        else:589            self.is_closed = False590            self.is_stream_consumed = False591            self._raw_stream = content592593        self.on_close = on_close594        self.request = request595        self.history = [] if history is None else list(history)596        self.next = None  # typing.Optional[typing.Callable]597598    @property599    def url(self) -> typing.Optional[URL]:600        """601        Returns the URL for which the request was made.602603        Requires that `request` was provided when instantiating the response.604        """605        return None if self.request is None else self.request.url606607    @property608    def content(self) -> bytes:609        if not hasattr(self, "_content"):610            if hasattr(self, "_raw_content"):611                content = self.decoder.decode(self._raw_content)612                content += self.decoder.flush()613                self._content = content614            else:615                raise ResponseNotRead()616        return self._content617618    @property619    def text(self) -> str:620        if not hasattr(self, "_text"):621            content = self.content622            if not content:623                self._text = ""624            else:625                encoding = self.encoding626                self._text = content.decode(encoding, errors="replace")627        return self._text628629    @property630    def encoding(self) -> str:631        if not hasattr(self, "_encoding"):632            encoding = self.charset_encoding633            if encoding is None or not is_known_encoding(encoding):634                encoding = self.apparent_encoding635                if encoding is None or not is_known_encoding(encoding):636                    encoding = "utf-8"637            self._encoding = encoding638        return self._encoding639640    @encoding.setter641    def encoding(self, value: str) -> None:642        self._encoding = value643644    @property645    def charset_encoding(self) -> typing.Optional[str]:646        """647        Return the encoding, as specified by the Content-Type header.648        """649        content_type = self.headers.get("Content-Type")650        if content_type is None:651            return None652653        parsed = cgi.parse_header(content_type)654        media_type, params = parsed[0], parsed[-1]655        if "charset" in params:656            return params["charset"].strip("'\"")657658        # RFC 2616 specifies that 'iso-8859-1' should be used as the default659        # for 'text/*' media types, if no charset is provided.660        # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1661        if media_type.startswith("text/"):662            return "iso-8859-1"663664        return None665666    @property667    def apparent_encoding(self) -> typing.Optional[str]:668        """669        Return the encoding, as it appears to autodetection.670        """671        return chardet.detect(self.content)["encoding"]672673    @property674    def decoder(self) -> Decoder:675        """676        Returns a decoder instance which can be used to decode the raw byte677        content, depending on the Content-Encoding used in the response.678        """679        if not hasattr(self, "_decoder"):680            decoders = []  # type: typing.List[Decoder]681            values = self.headers.getlist("content-encoding", split_commas=True)682            for value in values:683                value = value.strip().lower()684                decoder_cls = SUPPORTED_DECODERS[value]685                decoders.append(decoder_cls())686687            if len(decoders) == 1:688                self._decoder = decoders[0]689            elif len(decoders) > 1:690                self._decoder = MultiDecoder(decoders)691            else:692                self._decoder = IdentityDecoder()693694        return self._decoder695696    async def read(self) -> bytes:697        """698        Read and return the response content.699        """700        if not hasattr(self, "_content"):701            self._content = b"".join([part async for part in self.stream()])702        return self._content703704    async def stream(self) -> typing.AsyncIterator[bytes]:705        """706        A byte-iterator over the decoded response content.707        This allows us to handle gzip, deflate, and brotli encoded responses.708        """709        if hasattr(self, "_content"):710            yield self._content711        else:712            async for chunk in self.raw():713                yield self.decoder.decode(chunk)714            yield self.decoder.flush()715716    async def raw(self) -> typing.AsyncIterator[bytes]:717        """718        A byte-iterator over the raw response content.719        """720        if hasattr(self, "_raw_content"):721            yield self._raw_content722        else:723            if self.is_stream_consumed:724                raise StreamConsumed()725            if self.is_closed:726                raise ResponseClosed()727728            self.is_stream_consumed = True729            async for part in self._raw_stream:730                yield part731            await self.close()732733    async def close(self) -> None:734        """735        Close the response and release the connection.736        Automatically called if the response body is read to completion.737        """738        if not self.is_closed:739            self.is_closed = True740            if self.on_close is not None:741                await self.on_close()742743    @property744    def is_redirect(self) -> bool:745        return (746            self.status_code747            in (748                codes.MOVED_PERMANENTLY,749                codes.FOUND,750                codes.SEE_OTHER,751                codes.TEMPORARY_REDIRECT,752                codes.PERMANENT_REDIRECT,753            )754            and "location" in self.headers755        )756757    def raise_for_status(self) -> None:758        """759        Raise the `HttpError` if one occurred.760        """761        message = (762            "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"763            "For more information check: https://httpstatuses.com/{0.status_code}"764        )765766        if 400 <= self.status_code < 500:767            message = message.format(self, error_type="Client Error")768        elif 500 <= self.status_code < 600:769            message = message.format(self, error_type="Server Error")770        else:771            message = ""772773        if message:774            raise HttpError(message)775776    @property777    def cookies(self) -> "Cookies":778        if not hasattr(self, "_cookies"):779            assert self.request is not None780            self._cookies = Cookies()781            self._cookies.extract_cookies(self)782        return self._cookies783784    def __repr__(self) -> str:785        return f"<Response({self.status_code}, {self.reason_phrase!r})>"786787788class SyncResponse:789    """790    A thread-synchronous response. This class proxies onto a `Response`791    instance, providing standard synchronous interfaces where required.792    """793794    def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):795        self._response = response796        self._loop = loop797798    @property799    def status_code(self) -> int:800        return self._response.status_code801802    @property803    def reason_phrase(self) -> str:804        return self._response.reason_phrase805806    @property807    def protocol(self) -> typing.Optional[str]:808        return self._response.protocol809810    @property811    def url(self) -> typing.Optional[URL]:812        return self._response.url813814    @property815    def request(self) -> typing.Optional[Request]:816        return self._response.request817818    @property819    def headers(self) -> Headers:820        return self._response.headers821822    @property823    def content(self) -> bytes:824        return self._response.content825826    @property827    def text(self) -> str:828        return self._response.text829830    @property831    def encoding(self) -> str:832        return self._response.encoding833834    @property835    def is_redirect(self) -> bool:836        return self._response.is_redirect837838    def raise_for_status(self) -> None:839        return self._response.raise_for_status()840841    def read(self) -> bytes:842        return self._loop.run_until_complete(self._response.read())843844    def stream(self) -> typing.Iterator[bytes]:845        inner = self._response.stream()846        while True:847            try:848                yield self._loop.run_until_complete(inner.__anext__())849            except StopAsyncIteration:850                break851852    def raw(self) -> typing.Iterator[bytes]:853        inner = self._response.raw()854        while True:855            try:856                yield self._loop.run_until_complete(inner.__anext__())857            except StopAsyncIteration:858                break859860    def close(self) -> None:861        return self._loop.run_until_complete(self._response.close())862863    @property864    def cookies(self) -> "Cookies":865        return self._response.cookies866867    def __repr__(self) -> str:868        return f"<Response({self.status_code}, {self.reason_phrase!r})>"869870871class Cookies(MutableMapping):872    """873    HTTP Cookies, as a mutable mapping.874    """875876    def __init__(self, cookies: CookieTypes = None) -> None:877        if cookies is None or isinstance(cookies, dict):878            self.jar = CookieJar()879            if isinstance(cookies, dict):880                for key, value in cookies.items():881                    self.set(key, value)882        elif isinstance(cookies, Cookies):883            self.jar = CookieJar()884            for cookie in cookies.jar:885                self.jar.set_cookie(cookie)886        else:887            self.jar = cookies888889    def extract_cookies(self, response: Response) -> None:890        """891        Loads any cookies based on the response `Set-Cookie` headers.892        """893        assert response.request is not None894        urlib_response = self._CookieCompatResponse(response)895        urllib_request = self._CookieCompatRequest(response.request)896897        self.jar.extract_cookies(urlib_response, urllib_request)  # type: ignore898899    def set_cookie_header(self, request: Request) -> None:900        """901        Sets an appropriate 'Cookie:' HTTP header on the `Request`.902        """903        urllib_request = self._CookieCompatRequest(request)904        self.jar.add_cookie_header(urllib_request)905906    def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:907        """908        Set a cookie value by name. May optionally include domain and path.909        """910        kwargs = dict(911            version=0,912            name=name,913            value=value,914            port=None,915            port_specified=False,916            domain=domain,917            domain_specified=bool(domain),918            domain_initial_dot=domain.startswith("."),919            path=path,920            path_specified=bool(path),921            secure=False,922            expires=None,923            discard=True,924            comment=None,925            comment_url=None,926            rest={"HttpOnly": None},927            rfc2109=False,928        )929        cookie = Cookie(**kwargs)  # type: ignore930        self.jar.set_cookie(cookie)931932    def get(  # type: ignore933        self, name: str, default: str = None, domain: str = None, path: str = None934    ) -> typing.Optional[str]:935        """936        Get a cookie by name. May optionally include domain and path937        in order to specify exactly which cookie to retrieve.938        """939        value = None940        for cookie in self.jar:941            if cookie.name == name:942                if domain is None or cookie.domain == domain:  # type: ignore943                    if path is None or cookie.path == path:944                        if value is not None:945                            message = f"Multiple cookies exist with name={name}"946                            raise CookieConflict(message)947                        value = cookie.value948949        if value is None:950            return default951        return value952953    def delete(self, name: str, domain: str = None, path: str = None) -> None:954        """955        Delete a cookie by name. May optionally include domain and path956        in order to specify exactly which cookie to delete.957        """958        if domain is not None and path is not None:959            return self.jar.clear(domain, path, name)960961        remove = []962        for cookie in self.jar:963            if cookie.name == name:964                if domain is None or cookie.domain == domain:  # type: ignore965                    if path is None or cookie.path == path:966                        remove.append(cookie)967968        for cookie in remove:969            self.jar.clear(cookie.domain, cookie.path, cookie.name)  # type: ignore970971    def clear(self, domain: str = None, path: str = None) -> None:972        """973        Delete all cookies. Optionally include a domain and path in974        order to only delete a subset of all the cookies.975        """976        args = []977        if domain is not None:978            args.append(domain)979        if path is not None:980            assert domain is not None981            args.append(path)982        self.jar.clear(*args)983984    def update(self, cookies: CookieTypes = None) -> None:  # type: ignore985        cookies = Cookies(cookies)986        for cookie in cookies.jar:987            self.jar.set_cookie(cookie)988989    def __setitem__(self, name: str, value: str) -> None:990        return self.set(name, value)991992    def __getitem__(self, name: str) -> str:993        value = self.get(name)994        if value is None:995            raise KeyError(name)996        return value997998    def __delitem__(self, name: str) -> None:999        return self.delete(name)10001001    def __len__(self) -> int:1002        return len(self.jar)10031004    def __iter__(self) -> typing.Iterator[str]:1005        return (cookie.name for cookie in self.jar)10061007    def __bool__(self) -> bool:1008        for cookie in self.jar:1009            return True1010        return False10111012    class _CookieCompatRequest(urllib.request.Request):1013        """1014        Wraps a `Request` instance up in a compatability interface suitable1015        for use with `CookieJar` operations.1016        """10171018        def __init__(self, request: Request) -> None:1019            super().__init__(1020                url=str(request.url),1021                headers=dict(request.headers),1022                method=request.method,1023            )1024            self.request = request10251026        def add_unredirected_header(self, key: str, value: str) -> None:1027            super().add_unredirected_header(key, value)1028            self.request.headers[key] = value10291030    class _CookieCompatResponse:1031        """1032        Wraps a `Request` instance up in a compatability interface suitable1033        for use with `CookieJar` operations.1034        """10351036        def __init__(self, response: Response):1037            self.response = response10381039        def info(self) -> email.message.Message:1040            info = email.message.Message()1041            for key, value in self.response.headers.items():1042                info[key] = value1043            return info