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 fileTake it
Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 1why, one step back1import asyncioAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
line 2why, one step back2import cgiCookie support (#73)Tom Christiebefore adoptionfeae0a8
line 3why, one step back3import email.messageMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 4why, one step back4import typingCookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 5–7why, one step back5import urllib.request6from collections.abc import MutableMapping7from http.cookiejar import Cookie, CookieJarMerge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 8why, one step back8from urllib.parse import parse_qsl, urlencodeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 9why, one step back9Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 10why, one step back10import chardetUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 11why, one step back11import rfc3986Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 12why, one step back12Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 13–19why, one step back13from .decoders import (14 ACCEPT_ENCODING,15 SUPPORTED_DECODERS,16 Decoder,17 IdentityDecoder,18 MultiDecoder,19)Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
line 20why, one step back20from .exceptions import (Cookie support (#73)Tom Christiebefore adoptionfeae0a8
line 21why, one step back21 CookieConflict,Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 22–27why, one step back22 HttpError,23 InvalidURL,24 ResponseClosed,25 ResponseNotRead,26 StreamConsumed,27)Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369
line 28why, one step back28from .status_codes import codesAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 29–34why, one step back29from .utils import (30 get_reason_phrase,31 is_known_encoding,32 normalize_header_key,33 normalize_header_value,34)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 35why, one step back35Finessing interfaceTom Christiebefore adoptiond7619a9
line 36why, one step back36URLTypes = typing.Union["URL", str]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 37why, one step back37Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 38–44why, one step back38QueryParamTypes = typing.Union[39 "QueryParams",40 typing.Mapping[str, str],41 typing.List[typing.Tuple[typing.Any, typing.Any]],42 str,43]44Finessing interfaceTom Christiebefore adoptiond7619a9
lines 45–50why, one step back45HeaderTypes = typing.Union[46 "Headers",47 typing.Dict[typing.AnyStr, typing.AnyStr],48 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],49]50Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 51–52why, one step back51CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]52Auth (#65)Tom Christiebefore adoption5afa7dd
lines 53–54why, one step back53AuthTypes = typing.Union[54 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 55why, one step back55 typing.Callable[["Request"], "Request"],Auth (#65)Tom Christiebefore adoption5afa7dd
lines 56–57why, one step back56]57Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 58why, one step back58RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 59why, one step back59Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 60why, one step back60ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 61why, one step back61Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 62why, one step back62Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 63why, one step back63class URL:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 64–67why, one step back64 def __init__(65 self,66 url: URLTypes,67 allow_relative: bool = False,query_params -> paramsTom Christiebefore adoptionbb70377
line 68why, one step back68 params: QueryParamTypes = None,Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 69why, one step back69 ) -> None:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 70why, one step back70 if isinstance(url, rfc3986.uri.URIReference):Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 71why, one step back71 self.components = urlAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 72–73why, one step back72 elif isinstance(url, str):73 self.components = rfc3986.api.uri_reference(url)Finessing interfaceTom Christiebefore adoptiond7619a9
lines 74–76why, one step back74 else:75 self.components = url.components76Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 77–82why, one step back77 # 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)82Fix docstringsTom Christiebefore adoption8a227c1
line 83why, one step back83 # Normalize scheme and domain name.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 84–85why, one step back84 self.components = self.components.normalize()85Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 86why, one step back86 # Add any query parameters.query_params -> paramsTom Christiebefore adoptionbb70377
lines 87–88why, one step back87 if params:88 query_string = str(QueryParams(params))Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 89–90why, one step back89 self.components = self.components.copy_with(query=query_string)90Add idna support. More tests.Tom Christiebefore adoptionb948798
line 91why, one step back91 # Enforce absolute URLs by default.Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 92–97why, one step back92 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:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 98why, one step back98 raise InvalidURL("No host included in URL.")Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 99–101why, one step back99100 @property101 def scheme(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 102why, one step back102 return self.components.scheme or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 103–104why, one step back103104 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 105–106why, one step back105 def authority(self) -> str:106 return self.components.authority or ""Auth (#65)Tom Christiebefore adoption5afa7dd
lines 107–110why, one step back107108 @property109 def username(self) -> str:110 userinfo = self.components.userinfo or ""Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 111why, one step back111 return userinfo.partition(":")[0]Auth (#65)Tom Christiebefore adoption5afa7dd
lines 112–115why, one step back112113 @property114 def password(self) -> str:115 userinfo = self.components.userinfo or ""Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 116why, one step back116 return userinfo.partition(":")[2]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 117–118why, one step back117118 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 119–120why, one step back119 def host(self) -> str:120 return self.components.host or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 121–126why, one step back121122 @property123 def port(self) -> int:124 port = self.components.port125 if port is None:126 return {"https": 443, "http": 80}[self.scheme]Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 127why, one step back127 return int(port)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 128–129why, one step back128129 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 130–137why, one step back130 def path(self) -> str:131 return self.components.path or "/"132133 @property134 def query(self) -> str:135 return self.components.query or ""136137 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 138why, one step back138 def full_path(self) -> str:Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
lines 139–141why, one step back139 path = self.path140 if self.query:141 path += "?" + self.queryMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 142–144why, one step back142 return path143144 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 145–148why, one step back145 def fragment(self) -> str:146 return self.components.fragment or ""147148 @propertyCarefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 149why, one step back149 def is_ssl(self) -> bool:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 150–152why, one step back150 return self.components.scheme == "https"151152 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 153–162why, one step back153 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.hostUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 163–164why, one step back163164 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 165–168why, one step back165 def is_relative_url(self) -> bool:166 return not self.is_absolute_url167168 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 169–171why, one step back169 def origin(self) -> "Origin":170 return Origin(self)171Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 172–175why, one step back172 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":Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 176–179why, one step back176 """177 Return an absolute URL, using base_url as the base.178 """179 # We drop any fragment portion, because RFC 3986 strictlyFix docstringsTom Christiebefore adoption8a227c1
line 180why, one step back180 # treats URLs with a fragment portion as not being absolute URLs.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 181–182why, one step back181 base_url = URL(base_url).copy_with(fragment=None)182 return URL(self.components.resolve_with(base_url.components))Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 183why, one step back183Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 184–190why, one step back184 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:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 191why, one step back191 return self.components.unsplit()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 192–199why, one step back192193 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:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 200–203why, one step back200 """201 The URL scheme and authority information, as a comparable, hashable object.202 """203Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 204–205why, one step back204 def __init__(self, url: URLTypes) -> None:205 if not isinstance(url, URL):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 206why, one step back206 url = URL(url)Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 207why, one step back207 self.is_ssl = url.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 208why, one step back208 self.host = url.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 209–214why, one step back209 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_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 215why, one step back215 and self.host == other.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 216–219why, one step back216 and self.port == other.port217 )218219 def __hash__(self) -> int:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 220why, one step back220 return hash((self.is_ssl, self.host, self.port))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 221–222why, one step back221222Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 223why, one step back223class QueryParams(typing.Mapping[str, str]):Improve class __repr__Tom Christiebefore adoption666d5a8
lines 224–227why, one step back224 """225 URL query parameters, as a multi-dict.226 """227Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 228–291why, one step back228 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})"290291Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 292–293why, one step back292class Headers(typing.MutableMapping[str, str]):293 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 294why, one step back294 HTTP headers, as a case-insensitive multi-dict.Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 295–296why, one step back295 """296Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 297why, one step back297 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 298–303why, one step back298 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 = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 304why, one step back304 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 305–308why, one step back305 for k, v in headers.items()306 ]307 else:308 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 309–310why, one step back309 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))310 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 311why, one step back311 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 312why, one step back312 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 313–314why, one step back313314 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 315–316why, one step back315 def encoding(self) -> str:316 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 317–318why, one step back317 Header encoding is mandated as ascii, but we allow fallbacks to utf-8318 or iso-8859-1.Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 319–343why, one step back319 """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 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 344why, one step back344 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 345–348why, one step back345 """346 Returns a list of the raw header items, as byte pairs.347 May be mutated in-place.348 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 349–351why, one step back349 return self._list350351 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 352why, one step back352 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 353–354why, one step back353354 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 355why, one step back355 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 356–358why, one step back356357 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore358 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 359why, one step back359 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 360–368why, one step back360 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 default368Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 369why, one step back369 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 370–376why, one step back370 """371 Return multiple header values.372 """373 get_header_key = key.lower().encode(self.encoding)374375 values = [376 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 377–380why, one step back377 for item_key, item_value in self._list378 if item_key == get_header_key379 ]380Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 381–388why, one step back381 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_values388Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 389why, one step back389 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 390–398why, one step back390 """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 = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 399why, one step back399 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 400–405why, one step back400 if header_key == normalized_key:401 items.append(header_value.decode(self.encoding))402403 if items:404 return ", ".join(items)405Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 406–412why, one step back406 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 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 413–414why, one step back413 set_key = key.lower().encode(self.encoding)414 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 415–433why, one step back415416 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 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 434why, one step back434 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 435–444why, one step back435436 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:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 445why, one step back445 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 446–463why, one step back446 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__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 464–468why, one step back464465 encoding_str = ""466 if self.encoding != "ascii":467 encoding_str = f", encoding={self.encoding!r}"468Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 469–470why, one step back469 as_dict = dict(self.items())470 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 471–473why, one step back471 return f"{class_name}({as_dict!r}{encoding_str})"472 as_list = self.items()473 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 474–481why, one step back474475476class Request:477 def __init__(478 self,479 method: str,480 url: typing.Union[str, URL],481 *,Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 482why, one step back482 data: RequestData = b"",query_params -> paramsTom Christiebefore adoptionbb70377
line 483why, one step back483 params: QueryParamTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 484why, one step back484 headers: HeaderTypes = None,Cookie support (#73)Tom Christiebefore adoptionfeae0a8
line 485why, one step back485 cookies: CookieTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 486–487why, one step back486 ):487 self.method = method.upper()query_params -> paramsTom Christiebefore adoptionbb70377
line 488why, one step back488 self.url = URL(url, params=params)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 489why, one step back489 self.headers = Headers(headers)Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 490–492why, one step back490 if cookies:491 self._cookies = Cookies(cookies)492 self._cookies.set_cookie_header(self)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
lines 493–494why, one step back493494 if isinstance(data, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 495why, one step back495 self.is_streaming = FalseMerge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
lines 496–500why, one step back496 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"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 501–502why, one step back501 else:502 self.is_streaming = TrueMerge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 503why, one step back503 self.content_aiter = dataMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 504–508why, one step back504505 async def read(self) -> bytes:506 """507 Read and return the response content.508 """Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 509why, one step back509 if not hasattr(self, "content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 510why, one step back510 self.content = b"".join([part async for part in self.stream()])Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 511why, one step back511 return self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 512–514why, one step back512513 async def stream(self) -> typing.AsyncIterator[bytes]:514 if self.is_streaming:Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 515why, one step back515 async for part in self.content_aiter:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 516why, one step back516 yield partPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 517–518why, one step back517 elif self.content:518 yield self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 519–520why, one step back519520 def prepare(self) -> None:Response.contentTom Christiebefore adoption4c55113
lines 521–527why, one step back521 """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 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 528–535why, one step back528 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.headers535Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 536–537why, one step back536 if not has_host and self.url.authority:537 auto_headers.append((b"host", self.url.authority.encode("ascii")))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 538–540why, one step back538 if not has_content_length:539 if self.is_streaming:540 auto_headers.append((b"transfer-encoding", b"chunked"))Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 541–542why, one step back541 elif self.content:542 content_length = str(len(self.content)).encode()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 543–549why, one step back543 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)549Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 550–555why, one step back550 @property551 def cookies(self) -> "Cookies":552 if not hasattr(self, "_cookies"):553 self._cookies = Cookies()554 return self._cookies555Still truckin' onTom Christiebefore adoption6cb5c0d
lines 556–558why, one step back556 def __repr__(self) -> str:557 class_name = self.__class__.__name__558 url = str(self.url)Improve class __repr__Tom Christiebefore adoption666d5a8
line 559why, one step back559 return f"<{class_name}({self.method!r}, {url!r})>"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 560why, one step back560Still truckin' onTom Christiebefore adoption6cb5c0d
line 561why, one step back561Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 562–566why, one step back562class Response:563 def __init__(564 self,565 status_code: int,566 *,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 567–569why, one step back567 reason_phrase: str = None,568 protocol: str = None,569 headers: HeaderTypes = None,Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 570why, one step back570 content: ResponseContent = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 571–574why, one step back571 on_close: typing.Callable = None,572 request: Request = None,573 history: typing.List["Response"] = None,574 ):Truckin' onTom Christiebefore adoption6b60d95
lines 575–576why, one step back575 try:576 # Use a StatusCode IntEnum if possible, for a nicer representation.Still truckin' onTom Christiebefore adoption6cb5c0d
line 577why, one step back577 self.status_code = codes(status_code) # type: intTruckin' onTom Christiebefore adoption6b60d95
lines 578–579why, one step back578 except ValueError:579 self.status_code = status_codeResponse.contentTom Christiebefore adoption4c55113
line 580why, one step back580 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 581–583why, one step back581 self.protocol = protocol582 self.headers = Headers(headers)583Response.contentTom Christiebefore adoption4c55113
line 584why, one step back584 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 585why, one step back585 self.is_closed = TrueResponse.contentTom Christiebefore adoption4c55113
lines 586–587why, one step back586 self.is_stream_consumed = True587 self._raw_content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 588why, one step back588 else:Response.contentTom Christiebefore adoption4c55113
lines 589–591why, one step back589 self.is_closed = False590 self.is_stream_consumed = False591 self._raw_stream = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 592why, one step back592Response.contentTom Christiebefore adoption4c55113
line 593why, one step back593 self.on_close = on_closeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 594–595why, one step back594 self.request = request595 self.history = [] if history is None else list(history)response.next()Tom Christiebefore adoptiond652479
line 596why, one step back596 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 597–599why, one step back597598 @property599 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 600–604why, one step back600 """601 Returns the URL for which the request was made.602603 Requires that `request` was provided when instantiating the response.604 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 605why, one step back605 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 606–607why, one step back606607 @propertyResponse.contentTom Christiebefore adoption4c55113
lines 608–610why, one step back608 def content(self) -> bytes:609 if not hasattr(self, "_content"):610 if hasattr(self, "_raw_content"):Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 611–613why, one step back611 content = self.decoder.decode(self._raw_content)612 content += self.decoder.flush()613 self._content = contentResponse.contentTom Christiebefore adoption4c55113
lines 614–616why, one step back614 else:615 raise ResponseNotRead()616 return self._contentAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 617–652why, one step back617618 @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 None652Truckin' onTom Christiebefore adoption0ca1c84
lines 653–657why, one step back653 parsed = cgi.parse_header(content_type)654 media_type, params = parsed[0], parsed[-1]655 if "charset" in params:656 return params["charset"].strip("'\"")657Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 658–660why, one step back658 # 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.1Truckin' onTom Christiebefore adoption0ca1c84
lines 661–664why, one step back661 if media_type.startswith("text/"):662 return "iso-8859-1"663664 return NoneAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 665–671why, one step back665666 @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"]Response.contentTom Christiebefore adoption4c55113
lines 672–673why, one step back672673 @propertyClean up response interfaceTom Christiebefore adoption4d908d0
lines 674–680why, one step back674 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]Response.contentTom Christiebefore adoption4c55113
line 681why, one step back681 values = self.headers.getlist("content-encoding", split_commas=True)Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 682–684why, one step back682 for value in values:683 value = value.strip().lower()684 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 685–694why, one step back685 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._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 695–699why, one step back695696 async def read(self) -> bytes:697 """698 Read and return the response content.699 """Response.contentTom Christiebefore adoption4c55113
line 700why, one step back700 if not hasattr(self, "_content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 701why, one step back701 self._content = b"".join([part async for part in self.stream()])Response.contentTom Christiebefore adoption4c55113
line 702why, one step back702 return self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 703–708why, one step back703704 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 """Response.contentTom Christiebefore adoption4c55113
lines 709–710why, one step back709 if hasattr(self, "_content"):710 yield self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 711–719why, one step back711 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 """Response.contentTom Christiebefore adoption4c55113
lines 720–731why, one step back720 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()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 732–745why, one step back732733 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 (Finessing interfaceTom Christiebefore adoptiond7619a9
lines 746–747why, one step back746 self.status_code747 in (Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369
lines 748–752why, one step back748 codes.MOVED_PERMANENTLY,749 codes.FOUND,750 codes.SEE_OTHER,751 codes.TEMPORARY_REDIRECT,752 codes.PERMANENT_REDIRECT,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 753–754why, one step back753 )754 and "location" in self.headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 755why, one step back755 )Still truckin' onTom Christiebefore adoption6cb5c0d
line 756why, one step back756Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 757–774why, one step back757 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)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 775why, one step back775Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 776–783why, one step back776 @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._cookies783Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 784why, one step back784 def __repr__(self) -> str:repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
line 785why, one step back785 return f"<Response({self.status_code}, {self.reason_phrase!r})>"Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 786–848why, one step back786787788class 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__())Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e
line 849why, one step back849 except StopAsyncIteration:Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 850–856why, one step back850 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__())Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e
line 857why, one step back857 except StopAsyncIteration:Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 858–861why, one step back858 break859860 def close(self) -> None:861 return self._loop.run_until_complete(self._response.close())Merge pull request #56 from yeraydiazdiaz/test-additional-http-methodsTom Christiebefore adoption87cab4c
line 862why, one step back862Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 863–866why, one step back863 @property864 def cookies(self) -> "Cookies":865 return self._response.cookies866Merge pull request #56 from yeraydiazdiaz/test-additional-http-methodsTom Christiebefore adoption87cab4c
line 867why, one step back867 def __repr__(self) -> str:repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
line 868why, one step back868 return f"<Response({self.status_code}, {self.reason_phrase!r})>"Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 869–983why, one step back869870871class 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)983query_params -> paramsTom Christiebefore adoptionbb70377
line 984why, one step back984 def update(self, cookies: CookieTypes = None) -> None: # type: ignoreCookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 985–1043why, one step back985 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