models.py
This file
Path
httpcore/models.py
1,127 lines · 35.2 KiB · Python
Last changed by
Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
History of this fileTake it
Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 1why, one step back1import cgiCookie support (#73)Tom Christiebefore adoptionfeae0a8
line 2why, one step back2import email.messageAdd json interfacesTom Christiebefore adoption5a63d31
line 3why, one step back3import json as jsonlibMerge 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)Status code tweaks (#77)Tom Christiebefore adoptionc12c271
lines 28–29why, one step back28from .status_codes import StatusCode29from .utils import is_known_encoding, normalize_header_key, normalize_header_valueMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 30why, one step back30Finessing interfaceTom Christiebefore adoptiond7619a9
line 31why, one step back31URLTypes = typing.Union["URL", str]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 32why, one step back32Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 33–39why, one step back33QueryParamTypes = typing.Union[34 "QueryParams",35 typing.Mapping[str, str],36 typing.List[typing.Tuple[typing.Any, typing.Any]],37 str,38]39Finessing interfaceTom Christiebefore adoptiond7619a9
lines 40–45why, one step back40HeaderTypes = typing.Union[41 "Headers",42 typing.Dict[typing.AnyStr, typing.AnyStr],43 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],44]45Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 46–47why, one step back46CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]47Auth (#65)Tom Christiebefore adoption5afa7dd
lines 48–49why, one step back48AuthTypes = typing.Union[49 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 50why, one step back50 typing.Callable[["AsyncRequest"], "AsyncRequest"],Auth (#65)Tom Christiebefore adoption5afa7dd
lines 51–52why, one step back51]52Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 53why, one step back53AsyncRequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 54why, one step back54Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 55why, one step back55RequestData = typing.Union[dict, bytes, typing.Iterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 56why, one step back56Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 57why, one step back57AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 58why, one step back58Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 59–61why, one step back59ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]6061Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 62why, one step back62class URL:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 63–66why, one step back63 def __init__(64 self,65 url: URLTypes,66 allow_relative: bool = False,query_params -> paramsTom Christiebefore adoptionbb70377
line 67why, one step back67 params: QueryParamTypes = None,Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 68why, one step back68 ) -> None:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 69why, one step back69 if isinstance(url, rfc3986.uri.URIReference):Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 70why, one step back70 self.components = urlAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 71–72why, one step back71 elif isinstance(url, str):72 self.components = rfc3986.api.uri_reference(url)Finessing interfaceTom Christiebefore adoptiond7619a9
lines 73–75why, one step back73 else:74 self.components = url.components75Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 76–81why, one step back76 # Handle IDNA domain names.77 if self.components.authority:78 idna_authority = self.components.authority.encode("idna").decode("ascii")79 if idna_authority != self.components.authority:80 self.components = self.components.copy_with(authority=idna_authority)81Fix docstringsTom Christiebefore adoption8a227c1
line 82why, one step back82 # Normalize scheme and domain name.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 83–84why, one step back83 self.components = self.components.normalize()84Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 85why, one step back85 # Add any query parameters.query_params -> paramsTom Christiebefore adoptionbb70377
lines 86–87why, one step back86 if params:87 query_string = str(QueryParams(params))Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 88–89why, one step back88 self.components = self.components.copy_with(query=query_string)89Add idna support. More tests.Tom Christiebefore adoptionb948798
line 90why, one step back90 # Enforce absolute URLs by default.Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 91–96why, one step back91 if not allow_relative:92 if not self.scheme:93 raise InvalidURL("No scheme included in URL.")94 if self.scheme not in ("http", "https"):95 raise InvalidURL('URL scheme must be "http" or "https".')96 if not self.host:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 97why, one step back97 raise InvalidURL("No host included in URL.")Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 98–100why, one step back9899 @property100 def scheme(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 101why, one step back101 return self.components.scheme or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 102–103why, one step back102103 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 104–105why, one step back104 def authority(self) -> str:105 return self.components.authority or ""Auth (#65)Tom Christiebefore adoption5afa7dd
lines 106–109why, one step back106107 @property108 def username(self) -> str:109 userinfo = self.components.userinfo or ""Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 110why, one step back110 return userinfo.partition(":")[0]Auth (#65)Tom Christiebefore adoption5afa7dd
lines 111–114why, one step back111112 @property113 def password(self) -> str:114 userinfo = self.components.userinfo or ""Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 115why, one step back115 return userinfo.partition(":")[2]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 116–117why, one step back116117 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 118–119why, one step back118 def host(self) -> str:119 return self.components.host or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 120–125why, one step back120121 @property122 def port(self) -> int:123 port = self.components.port124 if port is None:125 return {"https": 443, "http": 80}[self.scheme]Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 126why, one step back126 return int(port)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 127–128why, one step back127128 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 129–136why, one step back129 def path(self) -> str:130 return self.components.path or "/"131132 @property133 def query(self) -> str:134 return self.components.query or ""135136 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 137why, one step back137 def full_path(self) -> str:Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
lines 138–140why, one step back138 path = self.path139 if self.query:140 path += "?" + self.queryMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 141–143why, one step back141 return path142143 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 144–147why, one step back144 def fragment(self) -> str:145 return self.components.fragment or ""146147 @propertyCarefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 148why, one step back148 def is_ssl(self) -> bool:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 149–151why, one step back149 return self.components.scheme == "https"150151 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 152–161why, one step back152 def is_absolute_url(self) -> bool:153 """154 Return `True` for absolute URLs such as 'http://example.com/path',155 and `False` for relative URLs such as '/path'.156 """157 # We don't use rfc3986's `is_absolute` because it treats158 # URLs with a fragment portion as not absolute.159 # What we actually care about is if the URL provides160 # a scheme and hostname to which connections should be made.161 return self.components.scheme and self.components.hostUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 162–163why, one step back162163 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 164–167why, one step back164 def is_relative_url(self) -> bool:165 return not self.is_absolute_url166167 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 168–170why, one step back168 def origin(self) -> "Origin":169 return Origin(self)170Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 171–174why, one step back171 def copy_with(self, **kwargs: typing.Any) -> "URL":172 return URL(self.components.copy_with(**kwargs))173174 def resolve_with(self, base_url: URLTypes) -> "URL":Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 175–178why, one step back175 """176 Return an absolute URL, using base_url as the base.177 """178 # We drop any fragment portion, because RFC 3986 strictlyFix docstringsTom Christiebefore adoption8a227c1
line 179why, one step back179 # treats URLs with a fragment portion as not being absolute URLs.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 180–181why, one step back180 base_url = URL(base_url).copy_with(fragment=None)181 return URL(self.components.resolve_with(base_url.components))Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 182why, one step back182Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 183–189why, one step back183 def __hash__(self) -> int:184 return hash(str(self))185186 def __eq__(self, other: typing.Any) -> bool:187 return isinstance(other, URL) and str(self) == str(other)188189 def __str__(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 190why, one step back190 return self.components.unsplit()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 191–198why, one step back191192 def __repr__(self) -> str:193 class_name = self.__class__.__name__194 url_str = str(self)195 return f"{class_name}({url_str!r})"196197198class Origin:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 199–202why, one step back199 """200 The URL scheme and authority information, as a comparable, hashable object.201 """202Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 203–204why, one step back203 def __init__(self, url: URLTypes) -> None:204 if not isinstance(url, URL):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 205why, one step back205 url = URL(url)Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 206why, one step back206 self.is_ssl = url.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 207why, one step back207 self.host = url.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 208–213why, one step back208 self.port = url.port209210 def __eq__(self, other: typing.Any) -> bool:211 return (212 isinstance(other, self.__class__)213 and self.is_ssl == other.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 214why, one step back214 and self.host == other.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 215–218why, one step back215 and self.port == other.port216 )217218 def __hash__(self) -> int:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 219why, one step back219 return hash((self.is_ssl, self.host, self.port))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 220–221why, one step back220221Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 222why, one step back222class QueryParams(typing.Mapping[str, str]):Improve class __repr__Tom Christiebefore adoption666d5a8
lines 223–226why, one step back223 """224 URL query parameters, as a multi-dict.225 """226Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 227–290why, one step back227 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:228 assert len(args) < 2, "Too many arguments."229 assert not (args and kwargs), "Cannot mix named and unnamed arguments."230231 value = args[0] if args else kwargs232233 if isinstance(value, str):234 items = parse_qsl(value)235 elif isinstance(value, QueryParams):236 items = value.multi_items()237 elif isinstance(value, list):238 items = value239 else:240 items = value.items() # type: ignore241242 self._list = [(str(k), str(v)) for k, v in items]243 self._dict = {str(k): str(v) for k, v in items}244245 def getlist(self, key: typing.Any) -> typing.List[str]:246 return [item_value for item_key, item_value in self._list if item_key == key]247248 def keys(self) -> typing.KeysView:249 return self._dict.keys()250251 def values(self) -> typing.ValuesView:252 return self._dict.values()253254 def items(self) -> typing.ItemsView:255 return self._dict.items()256257 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:258 return list(self._list)259260 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:261 if key in self._dict:262 return self._dict[key]263 return default264265 def __getitem__(self, key: typing.Any) -> str:266 return self._dict[key]267268 def __contains__(self, key: typing.Any) -> bool:269 return key in self._dict270271 def __iter__(self) -> typing.Iterator[typing.Any]:272 return iter(self.keys())273274 def __len__(self) -> int:275 return len(self._dict)276277 def __eq__(self, other: typing.Any) -> bool:278 if not isinstance(other, self.__class__):279 return False280 return sorted(self._list) == sorted(other._list)281282 def __str__(self) -> str:283 return urlencode(self._list)284285 def __repr__(self) -> str:286 class_name = self.__class__.__name__287 query_string = str(self)288 return f"{class_name}({query_string!r})"289290Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 291–292why, one step back291class Headers(typing.MutableMapping[str, str]):292 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 293why, one step back293 HTTP headers, as a case-insensitive multi-dict.Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 294–295why, one step back294 """295Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 296why, one step back296 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 297–302why, one step back297 if headers is None:298 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]299 elif isinstance(headers, Headers):300 self._list = list(headers.raw)301 elif isinstance(headers, dict):302 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 303why, one step back303 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 304–307why, one step back304 for k, v in headers.items()305 ]306 else:307 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 308–309why, one step back308 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))309 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 310why, one step back310 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 311why, one step back311 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 312–313why, one step back312313 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 314–315why, one step back314 def encoding(self) -> str:315 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 316–317why, one step back316 Header encoding is mandated as ascii, but we allow fallbacks to utf-8317 or iso-8859-1.Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 318–342why, one step back318 """319 if self._encoding is None:320 for encoding in ["ascii", "utf-8"]:321 for key, value in self.raw:322 try:323 key.decode(encoding)324 value.decode(encoding)325 except UnicodeDecodeError:326 break327 else:328 # The else block runs if 'break' did not occur, meaning329 # all values fitted the encoding.330 self._encoding = encoding331 break332 else:333 # The ISO-8859-1 encoding covers all 256 code points in a byte,334 # so will never raise decode errors.335 self._encoding = "iso-8859-1"336 return self._encoding337338 @encoding.setter339 def encoding(self, value: str) -> None:340 self._encoding = value341342 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 343why, one step back343 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 344–347why, one step back344 """345 Returns a list of the raw header items, as byte pairs.346 May be mutated in-place.347 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 348–350why, one step back348 return self._list349350 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 351why, one step back351 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 352–353why, one step back352353 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 354why, one step back354 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 355–357why, one step back355356 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore357 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 358why, one step back358 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 359–367why, one step back359 for key, value in self._list360 ]361362 def get(self, key: str, default: typing.Any = None) -> typing.Any:363 try:364 return self[key]365 except KeyError:366 return default367Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 368why, one step back368 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 369–375why, one step back369 """370 Return multiple header values.371 """372 get_header_key = key.lower().encode(self.encoding)373374 values = [375 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 376–379why, one step back376 for item_key, item_value in self._list377 if item_key == get_header_key378 ]379Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 380–387why, one step back380 if not split_commas:381 return values382383 split_values = []384 for value in values:385 split_values.extend([item.strip() for item in value.split(",")])386 return split_values387Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 388why, one step back388 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 389–397why, one step back389 """390 Return a single header value.391392 If there are multiple headers with the same key, then we concatenate393 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2394 """395 normalized_key = key.lower().encode(self.encoding)396397 items = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 398why, one step back398 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 399–404why, one step back399 if header_key == normalized_key:400 items.append(header_value.decode(self.encoding))401402 if items:403 return ", ".join(items)404Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 405–411why, one step back405 raise KeyError(key)406407 def __setitem__(self, key: str, value: str) -> None:408 """409 Set the header `key` to `value`, removing any duplicate entries.410 Retains insertion order.411 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 412–413why, one step back412 set_key = key.lower().encode(self.encoding)413 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 414–432why, one step back414415 found_indexes = []416 for idx, (item_key, item_value) in enumerate(self._list):417 if item_key == set_key:418 found_indexes.append(idx)419420 for idx in reversed(found_indexes[1:]):421 del self._list[idx]422423 if found_indexes:424 idx = found_indexes[0]425 self._list[idx] = (set_key, set_value)426 else:427 self._list.append((set_key, set_value))428429 def __delitem__(self, key: str) -> None:430 """431 Remove the header `key`.432 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 433why, one step back433 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 434–443why, one step back434435 pop_indexes = []436 for idx, (item_key, item_value) in enumerate(self._list):437 if item_key == del_key:438 pop_indexes.append(idx)439440 for idx in reversed(pop_indexes):441 del self._list[idx]442443 def __contains__(self, key: typing.Any) -> bool:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 444why, one step back444 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 445–462why, one step back445 for header_key, header_value in self._list:446 if header_key == get_header_key:447 return True448 return False449450 def __iter__(self) -> typing.Iterator[typing.Any]:451 return iter(self.keys())452453 def __len__(self) -> int:454 return len(self._list)455456 def __eq__(self, other: typing.Any) -> bool:457 if not isinstance(other, Headers):458 return False459 return sorted(self._list) == sorted(other._list)460461 def __repr__(self) -> str:462 class_name = self.__class__.__name__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 463–467why, one step back463464 encoding_str = ""465 if self.encoding != "ascii":466 encoding_str = f", encoding={self.encoding!r}"467Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 468–469why, one step back468 as_dict = dict(self.items())469 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 470–472why, one step back470 return f"{class_name}({as_dict!r}{encoding_str})"471 as_list = self.items()472 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 473–474why, one step back473474Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 475why, one step back475class BaseRequest:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 476–480why, one step back476 def __init__(477 self,478 method: str,479 url: typing.Union[str, URL],480 *,query_params -> paramsTom Christiebefore adoptionbb70377
line 481why, one step back481 params: QueryParamTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 482why, one step back482 headers: HeaderTypes = None,Cookie support (#73)Tom Christiebefore adoptionfeae0a8
line 483why, one step back483 cookies: CookieTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 484–485why, one step back484 ):485 self.method = method.upper()query_params -> paramsTom Christiebefore adoptionbb70377
line 486why, one step back486 self.url = URL(url, params=params)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 487why, one step back487 self.headers = Headers(headers)Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 488–490why, one step back488 if cookies:489 self._cookies = Cookies(cookies)490 self._cookies.set_cookie_header(self)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 491why, one step back491Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 492–554why, one step back492 def encode_json(self, json: typing.Any) -> bytes:493 return jsonlib.dumps(json).encode("utf-8")494495 def urlencode_data(self, data: dict) -> bytes:496 return urlencode(data, doseq=True).encode("utf-8")497498 def prepare(self) -> None:499 content = getattr(self, "content", None) # type: bytes500 is_streaming = getattr(self, "is_streaming", False)501502 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]503504 has_user_agent = "user-agent" in self.headers505 has_accept = "accept" in self.headers506 has_content_length = (507 "content-length" in self.headers or "transfer-encoding" in self.headers508 )509 has_accept_encoding = "accept-encoding" in self.headers510511 if not has_user_agent:512 auto_headers.append((b"user-agent", b"httpcore"))513 if not has_accept:514 auto_headers.append((b"accept", b"*/*"))515 if not has_content_length:516 if is_streaming:517 auto_headers.append((b"transfer-encoding", b"chunked"))518 elif content:519 content_length = str(len(content)).encode()520 auto_headers.append((b"content-length", content_length))521 if not has_accept_encoding:522 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))523524 for item in reversed(auto_headers):525 self.headers.raw.insert(0, item)526527 @property528 def cookies(self) -> "Cookies":529 if not hasattr(self, "_cookies"):530 self._cookies = Cookies()531 return self._cookies532533 def __repr__(self) -> str:534 class_name = self.__class__.__name__535 url = str(self.url)536 return f"<{class_name}({self.method!r}, {url!r})>"537538539class AsyncRequest(BaseRequest):540 def __init__(541 self,542 method: str,543 url: typing.Union[str, URL],544 *,545 params: QueryParamTypes = None,546 headers: HeaderTypes = None,547 cookies: CookieTypes = None,548 data: AsyncRequestData = b"",549 json: typing.Any = None,550 ):551 super().__init__(552 method=method, url=url, params=params, headers=headers, cookies=cookies553 )554Add json interfacesTom Christiebefore adoption5a63d31
line 555why, one step back555 if json is not None:Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 556–557why, one step back556 self.is_streaming = False557 self.content = self.encode_json(json)Add json interfacesTom Christiebefore adoption5a63d31
line 558why, one step back558 self.headers["Content-Type"] = "application/json"Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 559why, one step back559 elif isinstance(data, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 560why, one step back560 self.is_streaming = FalseMerge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
lines 561–563why, one step back561 self.content = data562 elif isinstance(data, dict):563 self.is_streaming = FalseSync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 564why, one step back564 self.content = self.urlencode_data(data)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 565why, one step back565 self.headers["Content-Type"] = "application/x-www-form-urlencoded"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 566why, one step back566 else:Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 567why, one step back567 assert hasattr(data, "__aiter__")Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 568why, one step back568 self.is_streaming = TrueMerge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 569why, one step back569 self.content_aiter = dataMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 570why, one step back570Drop prepare_requestTom Christiebefore adoption37da9ed
lines 571–572why, one step back571 self.prepare()572Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 573–576why, one step back573 async def read(self) -> bytes:574 """575 Read and return the response content.576 """Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 577why, one step back577 if not hasattr(self, "content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 578why, one step back578 self.content = b"".join([part async for part in self.stream()])Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 579why, one step back579 return self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 580–582why, one step back580581 async def stream(self) -> typing.AsyncIterator[bytes]:582 if self.is_streaming:Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 583why, one step back583 async for part in self.content_aiter:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 584why, one step back584 yield partPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 585–586why, one step back585 elif self.content:586 yield self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 587–588why, one step back587588Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 589–602why, one step back589class Request(BaseRequest):590 def __init__(591 self,592 method: str,593 url: typing.Union[str, URL],594 *,595 params: QueryParamTypes = None,596 headers: HeaderTypes = None,597 cookies: CookieTypes = None,598 data: RequestData = b"",599 json: typing.Any = None,600 ):601 super().__init__(602 method=method, url=url, params=params, headers=headers, cookies=cookiesMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 603–604why, one step back603 )604Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 605–619why, one step back605 if json is not None:606 self.is_streaming = False607 self.content = self.encode_json(json)608 self.headers["Content-Type"] = "application/json"609 elif isinstance(data, bytes):610 self.is_streaming = False611 self.content = data612 elif isinstance(data, dict):613 self.is_streaming = False614 self.content = self.urlencode_data(data)615 self.headers["Content-Type"] = "application/x-www-form-urlencoded"616 else:617 assert hasattr(data, "__iter__")618 self.is_streaming = True619 self.content_iter = dataMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 620why, one step back620Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 621why, one step back621 self.prepare()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 622why, one step back622Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 623–626why, one step back623 def read(self) -> bytes:624 if not hasattr(self, "content"):625 self.content = b"".join([part for part in self.stream()])626 return self.contentCookie support (#73)Tom Christiebefore adoptionfeae0a8
line 627why, one step back627Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 628–633why, one step back628 def stream(self) -> typing.Iterator[bytes]:629 if self.is_streaming:630 for part in self.content_iter:631 yield part632 elif self.content:633 yield self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 634why, one step back634Still truckin' onTom Christiebefore adoption6cb5c0d
line 635why, one step back635Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 636why, one step back636class BaseResponse:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 637–640why, one step back637 def __init__(638 self,639 status_code: int,640 *,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 641–643why, one step back641 reason_phrase: str = None,642 protocol: str = None,643 headers: HeaderTypes = None,Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 644why, one step back644 request: BaseRequest = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 645–646why, one step back645 on_close: typing.Callable = None,646 ):Status code tweaks (#77)Tom Christiebefore adoptionc12c271
lines 647–648why, one step back647 self.status_code = StatusCode.enum_or_int(status_code)648 self.reason_phrase = StatusCode.get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 649–652why, one step back649 self.protocol = protocol650 self.headers = Headers(headers)651652 self.request = requestSync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 653why, one step back653 self.on_close = on_closeresponse.next()Tom Christiebefore adoptiond652479
line 654why, one step back654 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 655–657why, one step back655656 @property657 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 658–662why, one step back658 """659 Returns the URL for which the request was made.660661 Requires that `request` was provided when instantiating the response.662 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 663why, one step back663 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 664–665why, one step back664665 @propertyResponse.contentTom Christiebefore adoption4c55113
lines 666–668why, one step back666 def content(self) -> bytes:667 if not hasattr(self, "_content"):668 if hasattr(self, "_raw_content"):Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 669–670why, one step back669 raw_content = getattr(self, "_raw_content") # type: bytes670 content = self.decoder.decode(raw_content)Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 671–672why, one step back671 content += self.decoder.flush()672 self._content = contentResponse.contentTom Christiebefore adoption4c55113
lines 673–675why, one step back673 else:674 raise ResponseNotRead()675 return self._contentAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 676–711why, one step back676677 @property678 def text(self) -> str:679 if not hasattr(self, "_text"):680 content = self.content681 if not content:682 self._text = ""683 else:684 encoding = self.encoding685 self._text = content.decode(encoding, errors="replace")686 return self._text687688 @property689 def encoding(self) -> str:690 if not hasattr(self, "_encoding"):691 encoding = self.charset_encoding692 if encoding is None or not is_known_encoding(encoding):693 encoding = self.apparent_encoding694 if encoding is None or not is_known_encoding(encoding):695 encoding = "utf-8"696 self._encoding = encoding697 return self._encoding698699 @encoding.setter700 def encoding(self, value: str) -> None:701 self._encoding = value702703 @property704 def charset_encoding(self) -> typing.Optional[str]:705 """706 Return the encoding, as specified by the Content-Type header.707 """708 content_type = self.headers.get("Content-Type")709 if content_type is None:710 return None711Truckin' onTom Christiebefore adoption0ca1c84
lines 712–716why, one step back712 parsed = cgi.parse_header(content_type)713 media_type, params = parsed[0], parsed[-1]714 if "charset" in params:715 return params["charset"].strip("'\"")716Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 717–719why, one step back717 # RFC 2616 specifies that 'iso-8859-1' should be used as the default718 # for 'text/*' media types, if no charset is provided.719 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1Truckin' onTom Christiebefore adoption0ca1c84
lines 720–723why, one step back720 if media_type.startswith("text/"):721 return "iso-8859-1"722723 return NoneAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 724–730why, one step back724725 @property726 def apparent_encoding(self) -> typing.Optional[str]:727 """728 Return the encoding, as it appears to autodetection.729 """730 return chardet.detect(self.content)["encoding"]Response.contentTom Christiebefore adoption4c55113
lines 731–732why, one step back731732 @propertyClean up response interfaceTom Christiebefore adoption4d908d0
lines 733–739why, one step back733 def decoder(self) -> Decoder:734 """735 Returns a decoder instance which can be used to decode the raw byte736 content, depending on the Content-Encoding used in the response.737 """738 if not hasattr(self, "_decoder"):739 decoders = [] # type: typing.List[Decoder]Response.contentTom Christiebefore adoption4c55113
line 740why, one step back740 values = self.headers.getlist("content-encoding", split_commas=True)Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 741–743why, one step back741 for value in values:742 value = value.strip().lower()743 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 744–753why, one step back744 decoders.append(decoder_cls())745746 if len(decoders) == 1:747 self._decoder = decoders[0]748 elif len(decoders) > 1:749 self._decoder = MultiDecoder(decoders)750 else:751 self._decoder = IdentityDecoder()752753 return self._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 754why, one step back754Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 755–825why, one step back755 @property756 def is_redirect(self) -> bool:757 return StatusCode.is_redirect(self.status_code) and "location" in self.headers758759 def raise_for_status(self) -> None:760 """761 Raise the `HttpError` if one occurred.762 """763 message = (764 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"765 "For more information check: https://httpstatuses.com/{0.status_code}"766 )767768 if StatusCode.is_client_error(self.status_code):769 message = message.format(self, error_type="Client Error")770 elif StatusCode.is_server_error(self.status_code):771 message = message.format(self, error_type="Server Error")772 else:773 message = ""774775 if message:776 raise HttpError(message)777778 def json(self) -> typing.Any:779 return jsonlib.loads(self.content.decode("utf-8"))780781 @property782 def cookies(self) -> "Cookies":783 if not hasattr(self, "_cookies"):784 assert self.request is not None785 self._cookies = Cookies()786 self._cookies.extract_cookies(self)787 return self._cookies788789 def __repr__(self) -> str:790 return f"<Response({self.status_code}, {self.reason_phrase!r})>"791792793class AsyncResponse(BaseResponse):794 def __init__(795 self,796 status_code: int,797 *,798 reason_phrase: str = None,799 protocol: str = None,800 headers: HeaderTypes = None,801 content: AsyncResponseContent = b"",802 on_close: typing.Callable = None,803 request: AsyncRequest = None,804 history: typing.List["BaseResponse"] = None,805 ):806 super().__init__(807 status_code=status_code,808 reason_phrase=reason_phrase,809 protocol=protocol,810 headers=headers,811 request=request,812 on_close=on_close,813 )814815 self.history = [] if history is None else list(history)816817 if isinstance(content, bytes):818 self.is_closed = True819 self.is_stream_consumed = True820 self._raw_content = content821 else:822 self.is_closed = False823 self.is_stream_consumed = False824 self._raw_stream = content825Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 826–829why, one step back826 async def read(self) -> bytes:827 """828 Read and return the response content.829 """Response.contentTom Christiebefore adoption4c55113
line 830why, one step back830 if not hasattr(self, "_content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 831why, one step back831 self._content = b"".join([part async for part in self.stream()])Response.contentTom Christiebefore adoption4c55113
line 832why, one step back832 return self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 833–838why, one step back833834 async def stream(self) -> typing.AsyncIterator[bytes]:835 """836 A byte-iterator over the decoded response content.837 This allows us to handle gzip, deflate, and brotli encoded responses.838 """Response.contentTom Christiebefore adoption4c55113
lines 839–840why, one step back839 if hasattr(self, "_content"):840 yield self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 841–849why, one step back841 else:842 async for chunk in self.raw():843 yield self.decoder.decode(chunk)844 yield self.decoder.flush()845846 async def raw(self) -> typing.AsyncIterator[bytes]:847 """848 A byte-iterator over the raw response content.849 """Response.contentTom Christiebefore adoption4c55113
lines 850–861why, one step back850 if hasattr(self, "_raw_content"):851 yield self._raw_content852 else:853 if self.is_stream_consumed:854 raise StreamConsumed()855 if self.is_closed:856 raise ResponseClosed()857858 self.is_stream_consumed = True859 async for part in self._raw_stream:860 yield part861 await self.close()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 862–872why, one step back862863 async def close(self) -> None:864 """865 Close the response and release the connection.866 Automatically called if the response body is read to completion.867 """868 if not self.is_closed:869 self.is_closed = True870 if self.on_close is not None:871 await self.on_close()872Still truckin' onTom Christiebefore adoption6cb5c0d
line 873why, one step back873Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 874–893why, one step back874class Response(BaseResponse):875 def __init__(876 self,877 status_code: int,878 *,879 reason_phrase: str = None,880 protocol: str = None,881 headers: HeaderTypes = None,882 content: ResponseContent = b"",883 on_close: typing.Callable = None,884 request: Request = None,885 history: typing.List["BaseResponse"] = None,886 ):887 super().__init__(888 status_code=status_code,889 reason_phrase=reason_phrase,890 protocol=protocol,891 headers=headers,892 request=request,893 on_close=on_close,Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 894–895why, one step back894 )895Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 896–901why, one step back896 self.history = [] if history is None else list(history)897898 if isinstance(content, bytes):899 self.is_closed = True900 self.is_stream_consumed = True901 self._raw_content = contentMerge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
line 902why, one step back902 else:Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 903–905why, one step back903 self.is_closed = False904 self.is_stream_consumed = False905 self._raw_stream = contentMerge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
line 906why, one step back906Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 907why, one step back907 def read(self) -> bytes:Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 908–913why, one step back908 """909 Read and return the response content.910 """911 if not hasattr(self, "_content"):912 self._content = b"".join([part for part in self.stream()])913 return self._contentMerge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 914–915why, one step back914915 def stream(self) -> typing.Iterator[bytes]:Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 916–925why, one step back916 """917 A byte-iterator over the decoded response content.918 This allows us to handle gzip, deflate, and brotli encoded responses.919 """920 if hasattr(self, "_content"):921 yield self._content922 else:923 for chunk in self.raw():924 yield self.decoder.decode(chunk)925 yield self.decoder.flush()Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 926–927why, one step back926927 def raw(self) -> typing.Iterator[bytes]:Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 928–937why, one step back928 """929 A byte-iterator over the raw response content.930 """931 if hasattr(self, "_raw_content"):932 yield self._raw_content933 else:934 if self.is_stream_consumed:935 raise StreamConsumed()936 if self.is_closed:937 raise ResponseClosed()Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 938why, one step back938Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 939–943why, one step back939 self.is_stream_consumed = True940 for part in self._raw_stream:941 yield part942 self.close()943Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 944why, one step back944 def close(self) -> None:Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 945–952why, one step back945 """946 Close the response and release the connection.947 Automatically called if the response body is read to completion.948 """949 if not self.is_closed:950 self.is_closed = True951 if self.on_close is not None:952 self.on_close()Merge pull request #56 from yeraydiazdiaz/test-additional-http-methodsTom Christiebefore adoption87cab4c
line 953why, one step back953Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 954–972why, one step back954955class Cookies(MutableMapping):956 """957 HTTP Cookies, as a mutable mapping.958 """959960 def __init__(self, cookies: CookieTypes = None) -> None:961 if cookies is None or isinstance(cookies, dict):962 self.jar = CookieJar()963 if isinstance(cookies, dict):964 for key, value in cookies.items():965 self.set(key, value)966 elif isinstance(cookies, Cookies):967 self.jar = CookieJar()968 for cookie in cookies.jar:969 self.jar.set_cookie(cookie)970 else:971 self.jar = cookies972Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 973why, one step back973 def extract_cookies(self, response: BaseResponse) -> None:Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 974–982why, one step back974 """975 Loads any cookies based on the response `Set-Cookie` headers.976 """977 assert response.request is not None978 urlib_response = self._CookieCompatResponse(response)979 urllib_request = self._CookieCompatRequest(response.request)980981 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore982Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 983why, one step back983 def set_cookie_header(self, request: BaseRequest) -> None:Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 984–1067why, one step back984 """985 Sets an appropriate 'Cookie:' HTTP header on the `Request`.986 """987 urllib_request = self._CookieCompatRequest(request)988 self.jar.add_cookie_header(urllib_request)989990 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:991 """992 Set a cookie value by name. May optionally include domain and path.993 """994 kwargs = dict(995 version=0,996 name=name,997 value=value,998 port=None,999 port_specified=False,1000 domain=domain,1001 domain_specified=bool(domain),1002 domain_initial_dot=domain.startswith("."),1003 path=path,1004 path_specified=bool(path),1005 secure=False,1006 expires=None,1007 discard=True,1008 comment=None,1009 comment_url=None,1010 rest={"HttpOnly": None},1011 rfc2109=False,1012 )1013 cookie = Cookie(**kwargs) # type: ignore1014 self.jar.set_cookie(cookie)10151016 def get( # type: ignore1017 self, name: str, default: str = None, domain: str = None, path: str = None1018 ) -> typing.Optional[str]:1019 """1020 Get a cookie by name. May optionally include domain and path1021 in order to specify exactly which cookie to retrieve.1022 """1023 value = None1024 for cookie in self.jar:1025 if cookie.name == name:1026 if domain is None or cookie.domain == domain: # type: ignore1027 if path is None or cookie.path == path:1028 if value is not None:1029 message = f"Multiple cookies exist with name={name}"1030 raise CookieConflict(message)1031 value = cookie.value10321033 if value is None:1034 return default1035 return value10361037 def delete(self, name: str, domain: str = None, path: str = None) -> None:1038 """1039 Delete a cookie by name. May optionally include domain and path1040 in order to specify exactly which cookie to delete.1041 """1042 if domain is not None and path is not None:1043 return self.jar.clear(domain, path, name)10441045 remove = []1046 for cookie in self.jar:1047 if cookie.name == name:1048 if domain is None or cookie.domain == domain: # type: ignore1049 if path is None or cookie.path == path:1050 remove.append(cookie)10511052 for cookie in remove:1053 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore10541055 def clear(self, domain: str = None, path: str = None) -> None:1056 """1057 Delete all cookies. Optionally include a domain and path in1058 order to only delete a subset of all the cookies.1059 """1060 args = []1061 if domain is not None:1062 args.append(domain)1063 if path is not None:1064 assert domain is not None1065 args.append(path)1066 self.jar.clear(*args)1067query_params -> paramsTom Christiebefore adoptionbb70377
line 1068why, one step back1068 def update(self, cookies: CookieTypes = None) -> None: # type: ignoreCookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 1069–1101why, one step back1069 cookies = Cookies(cookies)1070 for cookie in cookies.jar:1071 self.jar.set_cookie(cookie)10721073 def __setitem__(self, name: str, value: str) -> None:1074 return self.set(name, value)10751076 def __getitem__(self, name: str) -> str:1077 value = self.get(name)1078 if value is None:1079 raise KeyError(name)1080 return value10811082 def __delitem__(self, name: str) -> None:1083 return self.delete(name)10841085 def __len__(self) -> int:1086 return len(self.jar)10871088 def __iter__(self) -> typing.Iterator[str]:1089 return (cookie.name for cookie in self.jar)10901091 def __bool__(self) -> bool:1092 for cookie in self.jar:1093 return True1094 return False10951096 class _CookieCompatRequest(urllib.request.Request):1097 """1098 Wraps a `Request` instance up in a compatability interface suitable1099 for use with `CookieJar` operations.1100 """1101Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 1102why, one step back1102 def __init__(self, request: BaseRequest) -> None:Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 1103–1119why, one step back1103 super().__init__(1104 url=str(request.url),1105 headers=dict(request.headers),1106 method=request.method,1107 )1108 self.request = request11091110 def add_unredirected_header(self, key: str, value: str) -> None:1111 super().add_unredirected_header(key, value)1112 self.request.headers[key] = value11131114 class _CookieCompatResponse:1115 """1116 Wraps a `Request` instance up in a compatability interface suitable1117 for use with `CookieJar` operations.1118 """1119Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 1120why, one step back1120 def __init__(self, response: BaseResponse):Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 1121–1127why, one step back1121 self.response = response11221123 def info(self) -> email.message.Message:1124 info = email.message.Message()1125 for key, value in self.response.headers.items():1126 info[key] = value1127 return info