models.py
This file
Path
httpcore/models.py
1,036 lines · 32.3 KiB · Python
Last changed by
Status code tweaks (#77)Tom Christiebefore adoptionc12c271
History of this fileTake 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 async def read(self) -> bytes:507 """508 Read and return the response content.509 """510 if not hasattr(self, "content"):511 self.content = b"".join([part async for part in self.stream()])512 return self.content513514 async def stream(self) -> typing.AsyncIterator[bytes]:515 if self.is_streaming:516 async for part in self.content_aiter:517 yield part518 elif self.content:519 yield self.content520521 def prepare(self) -> None:522 """523 Adds in any default headers. When using the `Client`, this will524 end up being called into by the `prepare_request()` stage.525526 You can omit this behavior by calling `Client.send()` with an527 explicitly built `Request` instance.528 """529 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]530531 has_host = "host" in self.headers532 has_content_length = (533 "content-length" in self.headers or "transfer-encoding" in self.headers534 )535 has_accept_encoding = "accept-encoding" in self.headers536537 if not has_host and self.url.authority:538 auto_headers.append((b"host", self.url.authority.encode("ascii")))539 if not has_content_length:540 if self.is_streaming:541 auto_headers.append((b"transfer-encoding", b"chunked"))542 elif self.content:543 content_length = str(len(self.content)).encode()544 auto_headers.append((b"content-length", content_length))545 if not has_accept_encoding:546 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))547548 for item in reversed(auto_headers):549 self.headers.raw.insert(0, item)550551 @property552 def cookies(self) -> "Cookies":553 if not hasattr(self, "_cookies"):554 self._cookies = Cookies()555 return self._cookies556557 def __repr__(self) -> str:558 class_name = self.__class__.__name__559 url = str(self.url)560 return f"<{class_name}({self.method!r}, {url!r})>"561562563class Response:564 def __init__(565 self,566 status_code: int,567 *,568 reason_phrase: str = None,569 protocol: str = None,570 headers: HeaderTypes = None,571 content: ResponseContent = b"",572 on_close: typing.Callable = None,573 request: Request = None,574 history: typing.List["Response"] = None,575 ):576 self.status_code = StatusCode.enum_or_int(status_code)577 self.reason_phrase = StatusCode.get_reason_phrase(status_code)578 self.protocol = protocol579 self.headers = Headers(headers)580581 if isinstance(content, bytes):582 self.is_closed = True583 self.is_stream_consumed = True584 self._raw_content = content585 else:586 self.is_closed = False587 self.is_stream_consumed = False588 self._raw_stream = content589590 self.on_close = on_close591 self.request = request592 self.history = [] if history is None else list(history)593 self.next = None # typing.Optional[typing.Callable]594595 @property596 def url(self) -> typing.Optional[URL]:597 """598 Returns the URL for which the request was made.599600 Requires that `request` was provided when instantiating the response.601 """602 return None if self.request is None else self.request.url603604 @property605 def content(self) -> bytes:606 if not hasattr(self, "_content"):607 if hasattr(self, "_raw_content"):608 content = self.decoder.decode(self._raw_content)609 content += self.decoder.flush()610 self._content = content611 else:612 raise ResponseNotRead()613 return self._content614615 @property616 def text(self) -> str:617 if not hasattr(self, "_text"):618 content = self.content619 if not content:620 self._text = ""621 else:622 encoding = self.encoding623 self._text = content.decode(encoding, errors="replace")624 return self._text625626 @property627 def encoding(self) -> str:628 if not hasattr(self, "_encoding"):629 encoding = self.charset_encoding630 if encoding is None or not is_known_encoding(encoding):631 encoding = self.apparent_encoding632 if encoding is None or not is_known_encoding(encoding):633 encoding = "utf-8"634 self._encoding = encoding635 return self._encoding636637 @encoding.setter638 def encoding(self, value: str) -> None:639 self._encoding = value640641 @property642 def charset_encoding(self) -> typing.Optional[str]:643 """644 Return the encoding, as specified by the Content-Type header.645 """646 content_type = self.headers.get("Content-Type")647 if content_type is None:648 return None649650 parsed = cgi.parse_header(content_type)651 media_type, params = parsed[0], parsed[-1]652 if "charset" in params:653 return params["charset"].strip("'\"")654655 # RFC 2616 specifies that 'iso-8859-1' should be used as the default656 # for 'text/*' media types, if no charset is provided.657 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1658 if media_type.startswith("text/"):659 return "iso-8859-1"660661 return None662663 @property664 def apparent_encoding(self) -> typing.Optional[str]:665 """666 Return the encoding, as it appears to autodetection.667 """668 return chardet.detect(self.content)["encoding"]669670 @property671 def decoder(self) -> Decoder:672 """673 Returns a decoder instance which can be used to decode the raw byte674 content, depending on the Content-Encoding used in the response.675 """676 if not hasattr(self, "_decoder"):677 decoders = [] # type: typing.List[Decoder]678 values = self.headers.getlist("content-encoding", split_commas=True)679 for value in values:680 value = value.strip().lower()681 decoder_cls = SUPPORTED_DECODERS[value]682 decoders.append(decoder_cls())683684 if len(decoders) == 1:685 self._decoder = decoders[0]686 elif len(decoders) > 1:687 self._decoder = MultiDecoder(decoders)688 else:689 self._decoder = IdentityDecoder()690691 return self._decoder692693 async def read(self) -> bytes:694 """695 Read and return the response content.696 """697 if not hasattr(self, "_content"):698 self._content = b"".join([part async for part in self.stream()])699 return self._content700701 async def stream(self) -> typing.AsyncIterator[bytes]:702 """703 A byte-iterator over the decoded response content.704 This allows us to handle gzip, deflate, and brotli encoded responses.705 """706 if hasattr(self, "_content"):707 yield self._content708 else:709 async for chunk in self.raw():710 yield self.decoder.decode(chunk)711 yield self.decoder.flush()712713 async def raw(self) -> typing.AsyncIterator[bytes]:714 """715 A byte-iterator over the raw response content.716 """717 if hasattr(self, "_raw_content"):718 yield self._raw_content719 else:720 if self.is_stream_consumed:721 raise StreamConsumed()722 if self.is_closed:723 raise ResponseClosed()724725 self.is_stream_consumed = True726 async for part in self._raw_stream:727 yield part728 await self.close()729730 async def close(self) -> None:731 """732 Close the response and release the connection.733 Automatically called if the response body is read to completion.734 """735 if not self.is_closed:736 self.is_closed = True737 if self.on_close is not None:738 await self.on_close()739740 @property741 def is_redirect(self) -> bool:742 return StatusCode.is_redirect(self.status_code) and "location" in self.headers743744 def raise_for_status(self) -> None:745 """746 Raise the `HttpError` if one occurred.747 """748 message = (749 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"750 "For more information check: https://httpstatuses.com/{0.status_code}"751 )752753 if StatusCode.is_client_error(self.status_code):754 message = message.format(self, error_type="Client Error")755 elif StatusCode.is_server_error(self.status_code):756 message = message.format(self, error_type="Server Error")757 else:758 message = ""759760 if message:761 raise HttpError(message)762763 def json(self) -> typing.Any:764 return jsonlib.loads(self.content.decode("utf-8"))765766 @property767 def cookies(self) -> "Cookies":768 if not hasattr(self, "_cookies"):769 assert self.request is not None770 self._cookies = Cookies()771 self._cookies.extract_cookies(self)772 return self._cookies773774 def __repr__(self) -> str:775 return f"<Response({self.status_code}, {self.reason_phrase!r})>"776777778class SyncResponse:779 """780 A thread-synchronous response. This class proxies onto a `Response`781 instance, providing standard synchronous interfaces where required.782 """783784 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):785 self._response = response786 self._loop = loop787788 @property789 def status_code(self) -> int:790 return self._response.status_code791792 @property793 def reason_phrase(self) -> str:794 return self._response.reason_phrase795796 @property797 def protocol(self) -> typing.Optional[str]:798 return self._response.protocol799800 @property801 def url(self) -> typing.Optional[URL]:802 return self._response.url803804 @property805 def request(self) -> typing.Optional[Request]:806 return self._response.request807808 @property809 def headers(self) -> Headers:810 return self._response.headers811812 @property813 def content(self) -> bytes:814 return self._response.content815816 @property817 def text(self) -> str:818 return self._response.text819820 @property821 def encoding(self) -> str:822 return self._response.encoding823824 @property825 def is_redirect(self) -> bool:826 return self._response.is_redirect827828 def raise_for_status(self) -> None:829 return self._response.raise_for_status()830831 def json(self) -> typing.Any:832 return self._response.json()833834 def read(self) -> bytes:835 return self._loop.run_until_complete(self._response.read())836837 def stream(self) -> typing.Iterator[bytes]:838 inner = self._response.stream()839 while True:840 try:841 yield self._loop.run_until_complete(inner.__anext__())842 except StopAsyncIteration:843 break844845 def raw(self) -> typing.Iterator[bytes]:846 inner = self._response.raw()847 while True:848 try:849 yield self._loop.run_until_complete(inner.__anext__())850 except StopAsyncIteration:851 break852853 def close(self) -> None:854 return self._loop.run_until_complete(self._response.close())855856 @property857 def cookies(self) -> "Cookies":858 return self._response.cookies859860 def __repr__(self) -> str:861 return f"<Response({self.status_code}, {self.reason_phrase!r})>"862863864class Cookies(MutableMapping):865 """866 HTTP Cookies, as a mutable mapping.867 """868869 def __init__(self, cookies: CookieTypes = None) -> None:870 if cookies is None or isinstance(cookies, dict):871 self.jar = CookieJar()872 if isinstance(cookies, dict):873 for key, value in cookies.items():874 self.set(key, value)875 elif isinstance(cookies, Cookies):876 self.jar = CookieJar()877 for cookie in cookies.jar:878 self.jar.set_cookie(cookie)879 else:880 self.jar = cookies881882 def extract_cookies(self, response: Response) -> None:883 """884 Loads any cookies based on the response `Set-Cookie` headers.885 """886 assert response.request is not None887 urlib_response = self._CookieCompatResponse(response)888 urllib_request = self._CookieCompatRequest(response.request)889890 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore891892 def set_cookie_header(self, request: Request) -> None:893 """894 Sets an appropriate 'Cookie:' HTTP header on the `Request`.895 """896 urllib_request = self._CookieCompatRequest(request)897 self.jar.add_cookie_header(urllib_request)898899 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:900 """901 Set a cookie value by name. May optionally include domain and path.902 """903 kwargs = dict(904 version=0,905 name=name,906 value=value,907 port=None,908 port_specified=False,909 domain=domain,910 domain_specified=bool(domain),911 domain_initial_dot=domain.startswith("."),912 path=path,913 path_specified=bool(path),914 secure=False,915 expires=None,916 discard=True,917 comment=None,918 comment_url=None,919 rest={"HttpOnly": None},920 rfc2109=False,921 )922 cookie = Cookie(**kwargs) # type: ignore923 self.jar.set_cookie(cookie)924925 def get( # type: ignore926 self, name: str, default: str = None, domain: str = None, path: str = None927 ) -> typing.Optional[str]:928 """929 Get a cookie by name. May optionally include domain and path930 in order to specify exactly which cookie to retrieve.931 """932 value = None933 for cookie in self.jar:934 if cookie.name == name:935 if domain is None or cookie.domain == domain: # type: ignore936 if path is None or cookie.path == path:937 if value is not None:938 message = f"Multiple cookies exist with name={name}"939 raise CookieConflict(message)940 value = cookie.value941942 if value is None:943 return default944 return value945946 def delete(self, name: str, domain: str = None, path: str = None) -> None:947 """948 Delete a cookie by name. May optionally include domain and path949 in order to specify exactly which cookie to delete.950 """951 if domain is not None and path is not None:952 return self.jar.clear(domain, path, name)953954 remove = []955 for cookie in self.jar:956 if cookie.name == name:957 if domain is None or cookie.domain == domain: # type: ignore958 if path is None or cookie.path == path:959 remove.append(cookie)960961 for cookie in remove:962 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore963964 def clear(self, domain: str = None, path: str = None) -> None:965 """966 Delete all cookies. Optionally include a domain and path in967 order to only delete a subset of all the cookies.968 """969 args = []970 if domain is not None:971 args.append(domain)972 if path is not None:973 assert domain is not None974 args.append(path)975 self.jar.clear(*args)976977 def update(self, cookies: CookieTypes = None) -> None: # type: ignore978 cookies = Cookies(cookies)979 for cookie in cookies.jar:980 self.jar.set_cookie(cookie)981982 def __setitem__(self, name: str, value: str) -> None:983 return self.set(name, value)984985 def __getitem__(self, name: str) -> str:986 value = self.get(name)987 if value is None:988 raise KeyError(name)989 return value990991 def __delitem__(self, name: str) -> None:992 return self.delete(name)993994 def __len__(self) -> int:995 return len(self.jar)996997 def __iter__(self) -> typing.Iterator[str]:998 return (cookie.name for cookie in self.jar)9991000 def __bool__(self) -> bool:1001 for cookie in self.jar:1002 return True1003 return False10041005 class _CookieCompatRequest(urllib.request.Request):1006 """1007 Wraps a `Request` instance up in a compatability interface suitable1008 for use with `CookieJar` operations.1009 """10101011 def __init__(self, request: Request) -> None:1012 super().__init__(1013 url=str(request.url),1014 headers=dict(request.headers),1015 method=request.method,1016 )1017 self.request = request10181019 def add_unredirected_header(self, key: str, value: str) -> None:1020 super().add_unredirected_header(key, value)1021 self.request.headers[key] = value10221023 class _CookieCompatResponse:1024 """1025 Wraps a `Request` instance up in a compatability interface suitable1026 for use with `CookieJar` operations.1027 """10281029 def __init__(self, response: Response):1030 self.response = response10311032 def info(self) -> email.message.Message:1033 info = email.message.Message()1034 for key, value in self.response.headers.items():1035 info[key] = value1036 return info