Skip to content
Myr

models.py

This file

Path

httpcore/models.py

1,028 lines · 31.9 KiB · Python

Last changed by

Drop Host header for HTTP/2 (#82)Tom Christiebefore adoption76bc6c6

History of this file

Take it

1import asyncio2import cgi3import email.message4import json as jsonlib5import typing6import urllib.request7from collections.abc import MutableMapping8from http.cookiejar import Cookie, CookieJar9from urllib.parse import parse_qsl, urlencode1011import chardet12import rfc39861314from .decoders import (15    ACCEPT_ENCODING,16    SUPPORTED_DECODERS,17    Decoder,18    IdentityDecoder,19    MultiDecoder,20)21from .exceptions import (22    CookieConflict,23    HttpError,24    InvalidURL,25    ResponseClosed,26    ResponseNotRead,27    StreamConsumed,28)29from .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[["Request"], "Request"],52]5354RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]5556ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]575859class URL:60    def __init__(61        self,62        url: URLTypes,63        allow_relative: bool = False,64        params: QueryParamTypes = None,65    ) -> None:66        if isinstance(url, rfc3986.uri.URIReference):67            self.components = url68        elif isinstance(url, str):69            self.components = rfc3986.api.uri_reference(url)70        else:71            self.components = url.components7273        # Handle IDNA domain names.74        if self.components.authority:75            idna_authority = self.components.authority.encode("idna").decode("ascii")76            if idna_authority != self.components.authority:77                self.components = self.components.copy_with(authority=idna_authority)7879        # Normalize scheme and domain name.80        self.components = self.components.normalize()8182        # Add any query parameters.83        if params:84            query_string = str(QueryParams(params))85            self.components = self.components.copy_with(query=query_string)8687        # Enforce absolute URLs by default.88        if not allow_relative:89            if not self.scheme:90                raise InvalidURL("No scheme included in URL.")91            if self.scheme not in ("http", "https"):92                raise InvalidURL('URL scheme must be "http" or "https".')93            if not self.host:94                raise InvalidURL("No host included in URL.")9596    @property97    def scheme(self) -> str:98        return self.components.scheme or ""99100    @property101    def authority(self) -> str:102        return self.components.authority or ""103104    @property105    def username(self) -> str:106        userinfo = self.components.userinfo or ""107        return userinfo.partition(":")[0]108109    @property110    def password(self) -> str:111        userinfo = self.components.userinfo or ""112        return userinfo.partition(":")[2]113114    @property115    def host(self) -> str:116        return self.components.host or ""117118    @property119    def port(self) -> int:120        port = self.components.port121        if port is None:122            return {"https": 443, "http": 80}[self.scheme]123        return int(port)124125    @property126    def path(self) -> str:127        return self.components.path or "/"128129    @property130    def query(self) -> str:131        return self.components.query or ""132133    @property134    def full_path(self) -> str:135        path = self.path136        if self.query:137            path += "?" + self.query138        return path139140    @property141    def fragment(self) -> str:142        return self.components.fragment or ""143144    @property145    def is_ssl(self) -> bool:146        return self.components.scheme == "https"147148    @property149    def is_absolute_url(self) -> bool:150        """151        Return `True` for absolute URLs such as 'http://example.com/path',152        and `False` for relative URLs such as '/path'.153        """154        # We don't use rfc3986's `is_absolute` because it treats155        # URLs with a fragment portion as not absolute.156        # What we actually care about is if the URL provides157        # a scheme and hostname to which connections should be made.158        return self.components.scheme and self.components.host159160    @property161    def is_relative_url(self) -> bool:162        return not self.is_absolute_url163164    @property165    def origin(self) -> "Origin":166        return Origin(self)167168    def copy_with(self, **kwargs: typing.Any) -> "URL":169        return URL(self.components.copy_with(**kwargs))170171    def resolve_with(self, base_url: URLTypes) -> "URL":172        """173        Return an absolute URL, using base_url as the base.174        """175        # We drop any fragment portion, because RFC 3986 strictly176        # treats URLs with a fragment portion as not being absolute URLs.177        base_url = URL(base_url).copy_with(fragment=None)178        return URL(self.components.resolve_with(base_url.components))179180    def __hash__(self) -> int:181        return hash(str(self))182183    def __eq__(self, other: typing.Any) -> bool:184        return isinstance(other, URL) and str(self) == str(other)185186    def __str__(self) -> str:187        return self.components.unsplit()188189    def __repr__(self) -> str:190        class_name = self.__class__.__name__191        url_str = str(self)192        return f"{class_name}({url_str!r})"193194195class Origin:196    """197    The URL scheme and authority information, as a comparable, hashable object.198    """199200    def __init__(self, url: URLTypes) -> None:201        if not isinstance(url, URL):202            url = URL(url)203        self.is_ssl = url.is_ssl204        self.host = url.host205        self.port = url.port206207    def __eq__(self, other: typing.Any) -> bool:208        return (209            isinstance(other, self.__class__)210            and self.is_ssl == other.is_ssl211            and self.host == other.host212            and self.port == other.port213        )214215    def __hash__(self) -> int:216        return hash((self.is_ssl, self.host, self.port))217218219class QueryParams(typing.Mapping[str, str]):220    """221    URL query parameters, as a multi-dict.222    """223224    def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:225        assert len(args) < 2, "Too many arguments."226        assert not (args and kwargs), "Cannot mix named and unnamed arguments."227228        value = args[0] if args else kwargs229230        if isinstance(value, str):231            items = parse_qsl(value)232        elif isinstance(value, QueryParams):233            items = value.multi_items()234        elif isinstance(value, list):235            items = value236        else:237            items = value.items()  # type: ignore238239        self._list = [(str(k), str(v)) for k, v in items]240        self._dict = {str(k): str(v) for k, v in items}241242    def getlist(self, key: typing.Any) -> typing.List[str]:243        return [item_value for item_key, item_value in self._list if item_key == key]244245    def keys(self) -> typing.KeysView:246        return self._dict.keys()247248    def values(self) -> typing.ValuesView:249        return self._dict.values()250251    def items(self) -> typing.ItemsView:252        return self._dict.items()253254    def multi_items(self) -> typing.List[typing.Tuple[str, str]]:255        return list(self._list)256257    def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:258        if key in self._dict:259            return self._dict[key]260        return default261262    def __getitem__(self, key: typing.Any) -> str:263        return self._dict[key]264265    def __contains__(self, key: typing.Any) -> bool:266        return key in self._dict267268    def __iter__(self) -> typing.Iterator[typing.Any]:269        return iter(self.keys())270271    def __len__(self) -> int:272        return len(self._dict)273274    def __eq__(self, other: typing.Any) -> bool:275        if not isinstance(other, self.__class__):276            return False277        return sorted(self._list) == sorted(other._list)278279    def __str__(self) -> str:280        return urlencode(self._list)281282    def __repr__(self) -> str:283        class_name = self.__class__.__name__284        query_string = str(self)285        return f"{class_name}({query_string!r})"286287288class Headers(typing.MutableMapping[str, str]):289    """290    HTTP headers, as a case-insensitive multi-dict.291    """292293    def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:294        if headers is None:295            self._list = []  # type: typing.List[typing.Tuple[bytes, bytes]]296        elif isinstance(headers, Headers):297            self._list = list(headers.raw)298        elif isinstance(headers, dict):299            self._list = [300                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))301                for k, v in headers.items()302            ]303        else:304            self._list = [305                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))306                for k, v in headers307            ]308        self._encoding = encoding309310    @property311    def encoding(self) -> str:312        """313        Header encoding is mandated as ascii, but we allow fallbacks to utf-8314        or iso-8859-1.315        """316        if self._encoding is None:317            for encoding in ["ascii", "utf-8"]:318                for key, value in self.raw:319                    try:320                        key.decode(encoding)321                        value.decode(encoding)322                    except UnicodeDecodeError:323                        break324                else:325                    # The else block runs if 'break' did not occur, meaning326                    # all values fitted the encoding.327                    self._encoding = encoding328                    break329            else:330                # The ISO-8859-1 encoding covers all 256 code points in a byte,331                # so will never raise decode errors.332                self._encoding = "iso-8859-1"333        return self._encoding334335    @encoding.setter336    def encoding(self, value: str) -> None:337        self._encoding = value338339    @property340    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:341        """342        Returns a list of the raw header items, as byte pairs.343        May be mutated in-place.344        """345        return self._list346347    def keys(self) -> typing.List[str]:  # type: ignore348        return [key.decode(self.encoding) for key, value in self._list]349350    def values(self) -> typing.List[str]:  # type: ignore351        return [value.decode(self.encoding) for key, value in self._list]352353    def items(self) -> typing.List[typing.Tuple[str, str]]:  # type: ignore354        return [355            (key.decode(self.encoding), value.decode(self.encoding))356            for key, value in self._list357        ]358359    def get(self, key: str, default: typing.Any = None) -> typing.Any:360        try:361            return self[key]362        except KeyError:363            return default364365    def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:366        """367        Return multiple header values.368        """369        get_header_key = key.lower().encode(self.encoding)370371        values = [372            item_value.decode(self.encoding)373            for item_key, item_value in self._list374            if item_key == get_header_key375        ]376377        if not split_commas:378            return values379380        split_values = []381        for value in values:382            split_values.extend([item.strip() for item in value.split(",")])383        return split_values384385    def __getitem__(self, key: str) -> str:386        """387        Return a single header value.388389        If there are multiple headers with the same key, then we concatenate390        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2391        """392        normalized_key = key.lower().encode(self.encoding)393394        items = []395        for header_key, header_value in self._list:396            if header_key == normalized_key:397                items.append(header_value.decode(self.encoding))398399        if items:400            return ", ".join(items)401402        raise KeyError(key)403404    def __setitem__(self, key: str, value: str) -> None:405        """406        Set the header `key` to `value`, removing any duplicate entries.407        Retains insertion order.408        """409        set_key = key.lower().encode(self.encoding)410        set_value = value.encode(self.encoding)411412        found_indexes = []413        for idx, (item_key, item_value) in enumerate(self._list):414            if item_key == set_key:415                found_indexes.append(idx)416417        for idx in reversed(found_indexes[1:]):418            del self._list[idx]419420        if found_indexes:421            idx = found_indexes[0]422            self._list[idx] = (set_key, set_value)423        else:424            self._list.append((set_key, set_value))425426    def __delitem__(self, key: str) -> None:427        """428        Remove the header `key`.429        """430        del_key = key.lower().encode(self.encoding)431432        pop_indexes = []433        for idx, (item_key, item_value) in enumerate(self._list):434            if item_key == del_key:435                pop_indexes.append(idx)436437        for idx in reversed(pop_indexes):438            del self._list[idx]439440    def __contains__(self, key: typing.Any) -> bool:441        get_header_key = key.lower().encode(self.encoding)442        for header_key, header_value in self._list:443            if header_key == get_header_key:444                return True445        return False446447    def __iter__(self) -> typing.Iterator[typing.Any]:448        return iter(self.keys())449450    def __len__(self) -> int:451        return len(self._list)452453    def __eq__(self, other: typing.Any) -> bool:454        if not isinstance(other, Headers):455            return False456        return sorted(self._list) == sorted(other._list)457458    def __repr__(self) -> str:459        class_name = self.__class__.__name__460461        encoding_str = ""462        if self.encoding != "ascii":463            encoding_str = f", encoding={self.encoding!r}"464465        as_dict = dict(self.items())466        if len(as_dict) == len(self):467            return f"{class_name}({as_dict!r}{encoding_str})"468        as_list = self.items()469        return f"{class_name}({as_list!r}{encoding_str})"470471472class Request:473    def __init__(474        self,475        method: str,476        url: typing.Union[str, URL],477        *,478        data: RequestData = b"",479        json: typing.Any = None,480        params: QueryParamTypes = None,481        headers: HeaderTypes = None,482        cookies: CookieTypes = None,483    ):484        self.method = method.upper()485        self.url = URL(url, params=params)486        self.headers = Headers(headers)487        if cookies:488            self._cookies = Cookies(cookies)489            self._cookies.set_cookie_header(self)490491        if json is not None:492            data = jsonlib.dumps(json).encode("utf-8")493            self.headers["Content-Type"] = "application/json"494495        if isinstance(data, bytes):496            self.is_streaming = False497            self.content = data498        elif isinstance(data, dict):499            self.is_streaming = False500            self.content = urlencode(data, doseq=True).encode("utf-8")501            self.headers["Content-Type"] = "application/x-www-form-urlencoded"502        else:503            self.is_streaming = True504            self.content_aiter = data505506        self.prepare()507508    async def read(self) -> bytes:509        """510        Read and return the response content.511        """512        if not hasattr(self, "content"):513            self.content = b"".join([part async for part in self.stream()])514        return self.content515516    async def stream(self) -> typing.AsyncIterator[bytes]:517        if self.is_streaming:518            async for part in self.content_aiter:519                yield part520        elif self.content:521            yield self.content522523    def prepare(self) -> None:524        auto_headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]525526        has_content_length = (527            "content-length" in self.headers or "transfer-encoding" in self.headers528        )529        has_accept_encoding = "accept-encoding" in self.headers530531        if not has_content_length:532            if self.is_streaming:533                auto_headers.append((b"transfer-encoding", b"chunked"))534            elif self.content:535                content_length = str(len(self.content)).encode()536                auto_headers.append((b"content-length", content_length))537        if not has_accept_encoding:538            auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))539540        for item in reversed(auto_headers):541            self.headers.raw.insert(0, item)542543    @property544    def cookies(self) -> "Cookies":545        if not hasattr(self, "_cookies"):546            self._cookies = Cookies()547        return self._cookies548549    def __repr__(self) -> str:550        class_name = self.__class__.__name__551        url = str(self.url)552        return f"<{class_name}({self.method!r}, {url!r})>"553554555class Response:556    def __init__(557        self,558        status_code: int,559        *,560        reason_phrase: str = None,561        protocol: str = None,562        headers: HeaderTypes = None,563        content: ResponseContent = b"",564        on_close: typing.Callable = None,565        request: Request = None,566        history: typing.List["Response"] = None,567    ):568        self.status_code = StatusCode.enum_or_int(status_code)569        self.reason_phrase = StatusCode.get_reason_phrase(status_code)570        self.protocol = protocol571        self.headers = Headers(headers)572573        if isinstance(content, bytes):574            self.is_closed = True575            self.is_stream_consumed = True576            self._raw_content = content577        else:578            self.is_closed = False579            self.is_stream_consumed = False580            self._raw_stream = content581582        self.on_close = on_close583        self.request = request584        self.history = [] if history is None else list(history)585        self.next = None  # typing.Optional[typing.Callable]586587    @property588    def url(self) -> typing.Optional[URL]:589        """590        Returns the URL for which the request was made.591592        Requires that `request` was provided when instantiating the response.593        """594        return None if self.request is None else self.request.url595596    @property597    def content(self) -> bytes:598        if not hasattr(self, "_content"):599            if hasattr(self, "_raw_content"):600                content = self.decoder.decode(self._raw_content)601                content += self.decoder.flush()602                self._content = content603            else:604                raise ResponseNotRead()605        return self._content606607    @property608    def text(self) -> str:609        if not hasattr(self, "_text"):610            content = self.content611            if not content:612                self._text = ""613            else:614                encoding = self.encoding615                self._text = content.decode(encoding, errors="replace")616        return self._text617618    @property619    def encoding(self) -> str:620        if not hasattr(self, "_encoding"):621            encoding = self.charset_encoding622            if encoding is None or not is_known_encoding(encoding):623                encoding = self.apparent_encoding624                if encoding is None or not is_known_encoding(encoding):625                    encoding = "utf-8"626            self._encoding = encoding627        return self._encoding628629    @encoding.setter630    def encoding(self, value: str) -> None:631        self._encoding = value632633    @property634    def charset_encoding(self) -> typing.Optional[str]:635        """636        Return the encoding, as specified by the Content-Type header.637        """638        content_type = self.headers.get("Content-Type")639        if content_type is None:640            return None641642        parsed = cgi.parse_header(content_type)643        media_type, params = parsed[0], parsed[-1]644        if "charset" in params:645            return params["charset"].strip("'\"")646647        # RFC 2616 specifies that 'iso-8859-1' should be used as the default648        # for 'text/*' media types, if no charset is provided.649        # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1650        if media_type.startswith("text/"):651            return "iso-8859-1"652653        return None654655    @property656    def apparent_encoding(self) -> typing.Optional[str]:657        """658        Return the encoding, as it appears to autodetection.659        """660        return chardet.detect(self.content)["encoding"]661662    @property663    def decoder(self) -> Decoder:664        """665        Returns a decoder instance which can be used to decode the raw byte666        content, depending on the Content-Encoding used in the response.667        """668        if not hasattr(self, "_decoder"):669            decoders = []  # type: typing.List[Decoder]670            values = self.headers.getlist("content-encoding", split_commas=True)671            for value in values:672                value = value.strip().lower()673                decoder_cls = SUPPORTED_DECODERS[value]674                decoders.append(decoder_cls())675676            if len(decoders) == 1:677                self._decoder = decoders[0]678            elif len(decoders) > 1:679                self._decoder = MultiDecoder(decoders)680            else:681                self._decoder = IdentityDecoder()682683        return self._decoder684685    async def read(self) -> bytes:686        """687        Read and return the response content.688        """689        if not hasattr(self, "_content"):690            self._content = b"".join([part async for part in self.stream()])691        return self._content692693    async def stream(self) -> typing.AsyncIterator[bytes]:694        """695        A byte-iterator over the decoded response content.696        This allows us to handle gzip, deflate, and brotli encoded responses.697        """698        if hasattr(self, "_content"):699            yield self._content700        else:701            async for chunk in self.raw():702                yield self.decoder.decode(chunk)703            yield self.decoder.flush()704705    async def raw(self) -> typing.AsyncIterator[bytes]:706        """707        A byte-iterator over the raw response content.708        """709        if hasattr(self, "_raw_content"):710            yield self._raw_content711        else:712            if self.is_stream_consumed:713                raise StreamConsumed()714            if self.is_closed:715                raise ResponseClosed()716717            self.is_stream_consumed = True718            async for part in self._raw_stream:719                yield part720            await self.close()721722    async def close(self) -> None:723        """724        Close the response and release the connection.725        Automatically called if the response body is read to completion.726        """727        if not self.is_closed:728            self.is_closed = True729            if self.on_close is not None:730                await self.on_close()731732    @property733    def is_redirect(self) -> bool:734        return StatusCode.is_redirect(self.status_code) and "location" in self.headers735736    def raise_for_status(self) -> None:737        """738        Raise the `HttpError` if one occurred.739        """740        message = (741            "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"742            "For more information check: https://httpstatuses.com/{0.status_code}"743        )744745        if StatusCode.is_client_error(self.status_code):746            message = message.format(self, error_type="Client Error")747        elif StatusCode.is_server_error(self.status_code):748            message = message.format(self, error_type="Server Error")749        else:750            message = ""751752        if message:753            raise HttpError(message)754755    def json(self) -> typing.Any:756        return jsonlib.loads(self.content.decode("utf-8"))757758    @property759    def cookies(self) -> "Cookies":760        if not hasattr(self, "_cookies"):761            assert self.request is not None762            self._cookies = Cookies()763            self._cookies.extract_cookies(self)764        return self._cookies765766    def __repr__(self) -> str:767        return f"<Response({self.status_code}, {self.reason_phrase!r})>"768769770class SyncResponse:771    """772    A thread-synchronous response. This class proxies onto a `Response`773    instance, providing standard synchronous interfaces where required.774    """775776    def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):777        self._response = response778        self._loop = loop779780    @property781    def status_code(self) -> int:782        return self._response.status_code783784    @property785    def reason_phrase(self) -> str:786        return self._response.reason_phrase787788    @property789    def protocol(self) -> typing.Optional[str]:790        return self._response.protocol791792    @property793    def url(self) -> typing.Optional[URL]:794        return self._response.url795796    @property797    def request(self) -> typing.Optional[Request]:798        return self._response.request799800    @property801    def headers(self) -> Headers:802        return self._response.headers803804    @property805    def content(self) -> bytes:806        return self._response.content807808    @property809    def text(self) -> str:810        return self._response.text811812    @property813    def encoding(self) -> str:814        return self._response.encoding815816    @property817    def is_redirect(self) -> bool:818        return self._response.is_redirect819820    def raise_for_status(self) -> None:821        return self._response.raise_for_status()822823    def json(self) -> typing.Any:824        return self._response.json()825826    def read(self) -> bytes:827        return self._loop.run_until_complete(self._response.read())828829    def stream(self) -> typing.Iterator[bytes]:830        inner = self._response.stream()831        while True:832            try:833                yield self._loop.run_until_complete(inner.__anext__())834            except StopAsyncIteration:835                break836837    def raw(self) -> typing.Iterator[bytes]:838        inner = self._response.raw()839        while True:840            try:841                yield self._loop.run_until_complete(inner.__anext__())842            except StopAsyncIteration:843                break844845    def close(self) -> None:846        return self._loop.run_until_complete(self._response.close())847848    @property849    def cookies(self) -> "Cookies":850        return self._response.cookies851852    def __repr__(self) -> str:853        return f"<Response({self.status_code}, {self.reason_phrase!r})>"854855856class Cookies(MutableMapping):857    """858    HTTP Cookies, as a mutable mapping.859    """860861    def __init__(self, cookies: CookieTypes = None) -> None:862        if cookies is None or isinstance(cookies, dict):863            self.jar = CookieJar()864            if isinstance(cookies, dict):865                for key, value in cookies.items():866                    self.set(key, value)867        elif isinstance(cookies, Cookies):868            self.jar = CookieJar()869            for cookie in cookies.jar:870                self.jar.set_cookie(cookie)871        else:872            self.jar = cookies873874    def extract_cookies(self, response: Response) -> None:875        """876        Loads any cookies based on the response `Set-Cookie` headers.877        """878        assert response.request is not None879        urlib_response = self._CookieCompatResponse(response)880        urllib_request = self._CookieCompatRequest(response.request)881882        self.jar.extract_cookies(urlib_response, urllib_request)  # type: ignore883884    def set_cookie_header(self, request: Request) -> None:885        """886        Sets an appropriate 'Cookie:' HTTP header on the `Request`.887        """888        urllib_request = self._CookieCompatRequest(request)889        self.jar.add_cookie_header(urllib_request)890891    def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:892        """893        Set a cookie value by name. May optionally include domain and path.894        """895        kwargs = dict(896            version=0,897            name=name,898            value=value,899            port=None,900            port_specified=False,901            domain=domain,902            domain_specified=bool(domain),903            domain_initial_dot=domain.startswith("."),904            path=path,905            path_specified=bool(path),906            secure=False,907            expires=None,908            discard=True,909            comment=None,910            comment_url=None,911            rest={"HttpOnly": None},912            rfc2109=False,913        )914        cookie = Cookie(**kwargs)  # type: ignore915        self.jar.set_cookie(cookie)916917    def get(  # type: ignore918        self, name: str, default: str = None, domain: str = None, path: str = None919    ) -> typing.Optional[str]:920        """921        Get a cookie by name. May optionally include domain and path922        in order to specify exactly which cookie to retrieve.923        """924        value = None925        for cookie in self.jar:926            if cookie.name == name:927                if domain is None or cookie.domain == domain:  # type: ignore928                    if path is None or cookie.path == path:929                        if value is not None:930                            message = f"Multiple cookies exist with name={name}"931                            raise CookieConflict(message)932                        value = cookie.value933934        if value is None:935            return default936        return value937938    def delete(self, name: str, domain: str = None, path: str = None) -> None:939        """940        Delete a cookie by name. May optionally include domain and path941        in order to specify exactly which cookie to delete.942        """943        if domain is not None and path is not None:944            return self.jar.clear(domain, path, name)945946        remove = []947        for cookie in self.jar:948            if cookie.name == name:949                if domain is None or cookie.domain == domain:  # type: ignore950                    if path is None or cookie.path == path:951                        remove.append(cookie)952953        for cookie in remove:954            self.jar.clear(cookie.domain, cookie.path, cookie.name)  # type: ignore955956    def clear(self, domain: str = None, path: str = None) -> None:957        """958        Delete all cookies. Optionally include a domain and path in959        order to only delete a subset of all the cookies.960        """961        args = []962        if domain is not None:963            args.append(domain)964        if path is not None:965            assert domain is not None966            args.append(path)967        self.jar.clear(*args)968969    def update(self, cookies: CookieTypes = None) -> None:  # type: ignore970        cookies = Cookies(cookies)971        for cookie in cookies.jar:972            self.jar.set_cookie(cookie)973974    def __setitem__(self, name: str, value: str) -> None:975        return self.set(name, value)976977    def __getitem__(self, name: str) -> str:978        value = self.get(name)979        if value is None:980            raise KeyError(name)981        return value982983    def __delitem__(self, name: str) -> None:984        return self.delete(name)985986    def __len__(self) -> int:987        return len(self.jar)988989    def __iter__(self) -> typing.Iterator[str]:990        return (cookie.name for cookie in self.jar)991992    def __bool__(self) -> bool:993        for cookie in self.jar:994            return True995        return False996997    class _CookieCompatRequest(urllib.request.Request):998        """999        Wraps a `Request` instance up in a compatability interface suitable1000        for use with `CookieJar` operations.1001        """10021003        def __init__(self, request: Request) -> None:1004            super().__init__(1005                url=str(request.url),1006                headers=dict(request.headers),1007                method=request.method,1008            )1009            self.request = request10101011        def add_unredirected_header(self, key: str, value: str) -> None:1012            super().add_unredirected_header(key, value)1013            self.request.headers[key] = value10141015    class _CookieCompatResponse:1016        """1017        Wraps a `Request` instance up in a compatability interface suitable1018        for use with `CookieJar` operations.1019        """10201021        def __init__(self, response: Response):1022            self.response = response10231024        def info(self) -> email.message.Message:1025            info = email.message.Message()1026            for key, value in self.response.headers.items():1027                info[key] = value1028            return info