models.py
This file
Path
httpcore/models.py
1,036 lines · 32.3 KiB · Python
Last changed by
Status code tweaks (#77)Tom Christiebefore adoptionc12c271
History of this fileTake it
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.messageAdd json interfacesTom Christiebefore adoption5a63d31
line 4why, one step back4import json as jsonlibMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 5why, one step back5import typingCookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 6–8why, one step back6import urllib.request7from collections.abc import MutableMapping8from http.cookiejar import Cookie, CookieJarMerge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 9why, one step back9from urllib.parse import parse_qsl, urlencodeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 10why, one step back10Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 11why, one step back11import chardetUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 12why, one step back12import rfc3986Add response.text and response.encodingTom Christiebefore adoptiond8df61b
line 13why, one step back13Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 14–20why, one step back14from .decoders import (15 ACCEPT_ENCODING,16 SUPPORTED_DECODERS,17 Decoder,18 IdentityDecoder,19 MultiDecoder,20)Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
line 21why, one step back21from .exceptions import (Cookie support (#73)Tom Christiebefore adoptionfeae0a8
line 22why, one step back22 CookieConflict,Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 23–28why, one step back23 HttpError,24 InvalidURL,25 ResponseClosed,26 ResponseNotRead,27 StreamConsumed,28)Status code tweaks (#77)Tom Christiebefore adoptionc12c271
lines 29–30why, one step back29from .status_codes import StatusCode30from .utils import is_known_encoding, normalize_header_key, normalize_header_valueMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 31why, one step back31Finessing interfaceTom Christiebefore adoptiond7619a9
line 32why, one step back32URLTypes = typing.Union["URL", str]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 33why, one step back33Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 34–40why, one step back34QueryParamTypes = typing.Union[35 "QueryParams",36 typing.Mapping[str, str],37 typing.List[typing.Tuple[typing.Any, typing.Any]],38 str,39]40Finessing interfaceTom Christiebefore adoptiond7619a9
lines 41–46why, one step back41HeaderTypes = typing.Union[42 "Headers",43 typing.Dict[typing.AnyStr, typing.AnyStr],44 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],45]46Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 47–48why, one step back47CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]48Auth (#65)Tom Christiebefore adoption5afa7dd
lines 49–50why, one step back49AuthTypes = typing.Union[50 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 51why, one step back51 typing.Callable[["Request"], "Request"],Auth (#65)Tom Christiebefore adoption5afa7dd
lines 52–53why, one step back52]53Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 54why, one step back54RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 55why, one step back55Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 56why, one step back56ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 57why, one step back57Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 58why, one step back58Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 59why, one step back59class URL:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 60–63why, one step back60 def __init__(61 self,62 url: URLTypes,63 allow_relative: bool = False,query_params -> paramsTom Christiebefore adoptionbb70377
line 64why, one step back64 params: QueryParamTypes = None,Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 65why, one step back65 ) -> None:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 66why, one step back66 if isinstance(url, rfc3986.uri.URIReference):Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 67why, one step back67 self.components = urlAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 68–69why, one step back68 elif isinstance(url, str):69 self.components = rfc3986.api.uri_reference(url)Finessing interfaceTom Christiebefore adoptiond7619a9
lines 70–72why, one step back70 else:71 self.components = url.components72Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 73–78why, one step back73 # Handle IDNA domain names.74 if self.components.authority:75 idna_authority = self.components.authority.encode("idna").decode("ascii")76 if idna_authority != self.components.authority:77 self.components = self.components.copy_with(authority=idna_authority)78Fix docstringsTom Christiebefore adoption8a227c1
line 79why, one step back79 # Normalize scheme and domain name.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 80–81why, one step back80 self.components = self.components.normalize()81Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 82why, one step back82 # Add any query parameters.query_params -> paramsTom Christiebefore adoptionbb70377
lines 83–84why, one step back83 if params:84 query_string = str(QueryParams(params))Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 85–86why, one step back85 self.components = self.components.copy_with(query=query_string)86Add idna support. More tests.Tom Christiebefore adoptionb948798
line 87why, one step back87 # Enforce absolute URLs by default.Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 88–93why, one step back88 if not allow_relative:89 if not self.scheme:90 raise InvalidURL("No scheme included in URL.")91 if self.scheme not in ("http", "https"):92 raise InvalidURL('URL scheme must be "http" or "https".')93 if not self.host:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 94why, one step back94 raise InvalidURL("No host included in URL.")Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 95–97why, one step back9596 @property97 def scheme(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 98why, one step back98 return self.components.scheme or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 99–100why, one step back99100 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 101–102why, one step back101 def authority(self) -> str:102 return self.components.authority or ""Auth (#65)Tom Christiebefore adoption5afa7dd
lines 103–106why, one step back103104 @property105 def username(self) -> str:106 userinfo = self.components.userinfo or ""Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 107why, one step back107 return userinfo.partition(":")[0]Auth (#65)Tom Christiebefore adoption5afa7dd
lines 108–111why, one step back108109 @property110 def password(self) -> str:111 userinfo = self.components.userinfo or ""Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 112why, one step back112 return userinfo.partition(":")[2]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 113–114why, one step back113114 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 115–116why, one step back115 def host(self) -> str:116 return self.components.host or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 117–122why, one step back117118 @property119 def port(self) -> int:120 port = self.components.port121 if port is None:122 return {"https": 443, "http": 80}[self.scheme]Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 123why, one step back123 return int(port)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 124–125why, one step back124125 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 126–133why, one step back126 def path(self) -> str:127 return self.components.path or "/"128129 @property130 def query(self) -> str:131 return self.components.query or ""132133 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 134why, one step back134 def full_path(self) -> str:Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
lines 135–137why, one step back135 path = self.path136 if self.query:137 path += "?" + self.queryMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 138–140why, one step back138 return path139140 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 141–144why, one step back141 def fragment(self) -> str:142 return self.components.fragment or ""143144 @propertyCarefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 145why, one step back145 def is_ssl(self) -> bool:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 146–148why, one step back146 return self.components.scheme == "https"147148 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 149–158why, one step back149 def is_absolute_url(self) -> bool:150 """151 Return `True` for absolute URLs such as 'http://example.com/path',152 and `False` for relative URLs such as '/path'.153 """154 # We don't use rfc3986's `is_absolute` because it treats155 # URLs with a fragment portion as not absolute.156 # What we actually care about is if the URL provides157 # a scheme and hostname to which connections should be made.158 return self.components.scheme and self.components.hostUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 159–160why, one step back159160 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 161–164why, one step back161 def is_relative_url(self) -> bool:162 return not self.is_absolute_url163164 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 165–167why, one step back165 def origin(self) -> "Origin":166 return Origin(self)167Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 168–171why, one step back168 def copy_with(self, **kwargs: typing.Any) -> "URL":169 return URL(self.components.copy_with(**kwargs))170171 def resolve_with(self, base_url: URLTypes) -> "URL":Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 172–175why, one step back172 """173 Return an absolute URL, using base_url as the base.174 """175 # We drop any fragment portion, because RFC 3986 strictlyFix docstringsTom Christiebefore adoption8a227c1
line 176why, one step back176 # treats URLs with a fragment portion as not being absolute URLs.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 177–178why, one step back177 base_url = URL(base_url).copy_with(fragment=None)178 return URL(self.components.resolve_with(base_url.components))Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 179why, one step back179Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 180–186why, one step back180 def __hash__(self) -> int:181 return hash(str(self))182183 def __eq__(self, other: typing.Any) -> bool:184 return isinstance(other, URL) and str(self) == str(other)185186 def __str__(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 187why, one step back187 return self.components.unsplit()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 188–195why, one step back188189 def __repr__(self) -> str:190 class_name = self.__class__.__name__191 url_str = str(self)192 return f"{class_name}({url_str!r})"193194195class Origin:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 196–199why, one step back196 """197 The URL scheme and authority information, as a comparable, hashable object.198 """199Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 200–201why, one step back200 def __init__(self, url: URLTypes) -> None:201 if not isinstance(url, URL):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 202why, one step back202 url = URL(url)Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 203why, one step back203 self.is_ssl = url.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 204why, one step back204 self.host = url.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 205–210why, one step back205 self.port = url.port206207 def __eq__(self, other: typing.Any) -> bool:208 return (209 isinstance(other, self.__class__)210 and self.is_ssl == other.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 211why, one step back211 and self.host == other.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 212–215why, one step back212 and self.port == other.port213 )214215 def __hash__(self) -> int:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 216why, one step back216 return hash((self.is_ssl, self.host, self.port))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 217–218why, one step back217218Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 219why, one step back219class QueryParams(typing.Mapping[str, str]):Improve class __repr__Tom Christiebefore adoption666d5a8
lines 220–223why, one step back220 """221 URL query parameters, as a multi-dict.222 """223Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 224–287why, one step back224 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:225 assert len(args) < 2, "Too many arguments."226 assert not (args and kwargs), "Cannot mix named and unnamed arguments."227228 value = args[0] if args else kwargs229230 if isinstance(value, str):231 items = parse_qsl(value)232 elif isinstance(value, QueryParams):233 items = value.multi_items()234 elif isinstance(value, list):235 items = value236 else:237 items = value.items() # type: ignore238239 self._list = [(str(k), str(v)) for k, v in items]240 self._dict = {str(k): str(v) for k, v in items}241242 def getlist(self, key: typing.Any) -> typing.List[str]:243 return [item_value for item_key, item_value in self._list if item_key == key]244245 def keys(self) -> typing.KeysView:246 return self._dict.keys()247248 def values(self) -> typing.ValuesView:249 return self._dict.values()250251 def items(self) -> typing.ItemsView:252 return self._dict.items()253254 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:255 return list(self._list)256257 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:258 if key in self._dict:259 return self._dict[key]260 return default261262 def __getitem__(self, key: typing.Any) -> str:263 return self._dict[key]264265 def __contains__(self, key: typing.Any) -> bool:266 return key in self._dict267268 def __iter__(self) -> typing.Iterator[typing.Any]:269 return iter(self.keys())270271 def __len__(self) -> int:272 return len(self._dict)273274 def __eq__(self, other: typing.Any) -> bool:275 if not isinstance(other, self.__class__):276 return False277 return sorted(self._list) == sorted(other._list)278279 def __str__(self) -> str:280 return urlencode(self._list)281282 def __repr__(self) -> str:283 class_name = self.__class__.__name__284 query_string = str(self)285 return f"{class_name}({query_string!r})"286287Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 288–289why, one step back288class Headers(typing.MutableMapping[str, str]):289 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 290why, one step back290 HTTP headers, as a case-insensitive multi-dict.Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 291–292why, one step back291 """292Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 293why, one step back293 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 294–299why, one step back294 if headers is None:295 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]296 elif isinstance(headers, Headers):297 self._list = list(headers.raw)298 elif isinstance(headers, dict):299 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 300why, one step back300 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 301–304why, one step back301 for k, v in headers.items()302 ]303 else:304 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 305–306why, one step back305 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))306 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 307why, one step back307 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 308why, one step back308 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 309–310why, one step back309310 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 311–312why, one step back311 def encoding(self) -> str:312 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 313–314why, one step back313 Header encoding is mandated as ascii, but we allow fallbacks to utf-8314 or iso-8859-1.Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 315–339why, one step back315 """316 if self._encoding is None:317 for encoding in ["ascii", "utf-8"]:318 for key, value in self.raw:319 try:320 key.decode(encoding)321 value.decode(encoding)322 except UnicodeDecodeError:323 break324 else:325 # The else block runs if 'break' did not occur, meaning326 # all values fitted the encoding.327 self._encoding = encoding328 break329 else:330 # The ISO-8859-1 encoding covers all 256 code points in a byte,331 # so will never raise decode errors.332 self._encoding = "iso-8859-1"333 return self._encoding334335 @encoding.setter336 def encoding(self, value: str) -> None:337 self._encoding = value338339 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 340why, one step back340 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 341–344why, one step back341 """342 Returns a list of the raw header items, as byte pairs.343 May be mutated in-place.344 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 345–347why, one step back345 return self._list346347 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 348why, one step back348 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 349–350why, one step back349350 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 351why, one step back351 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 352–354why, one step back352353 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore354 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 355why, one step back355 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 356–364why, one step back356 for key, value in self._list357 ]358359 def get(self, key: str, default: typing.Any = None) -> typing.Any:360 try:361 return self[key]362 except KeyError:363 return default364Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 365why, one step back365 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 366–372why, one step back366 """367 Return multiple header values.368 """369 get_header_key = key.lower().encode(self.encoding)370371 values = [372 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 373–376why, one step back373 for item_key, item_value in self._list374 if item_key == get_header_key375 ]376Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 377–384why, one step back377 if not split_commas:378 return values379380 split_values = []381 for value in values:382 split_values.extend([item.strip() for item in value.split(",")])383 return split_values384Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 385why, one step back385 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 386–394why, one step back386 """387 Return a single header value.388389 If there are multiple headers with the same key, then we concatenate390 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2391 """392 normalized_key = key.lower().encode(self.encoding)393394 items = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 395why, one step back395 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 396–401why, one step back396 if header_key == normalized_key:397 items.append(header_value.decode(self.encoding))398399 if items:400 return ", ".join(items)401Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 402–408why, one step back402 raise KeyError(key)403404 def __setitem__(self, key: str, value: str) -> None:405 """406 Set the header `key` to `value`, removing any duplicate entries.407 Retains insertion order.408 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 409–410why, one step back409 set_key = key.lower().encode(self.encoding)410 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 411–429why, one step back411412 found_indexes = []413 for idx, (item_key, item_value) in enumerate(self._list):414 if item_key == set_key:415 found_indexes.append(idx)416417 for idx in reversed(found_indexes[1:]):418 del self._list[idx]419420 if found_indexes:421 idx = found_indexes[0]422 self._list[idx] = (set_key, set_value)423 else:424 self._list.append((set_key, set_value))425426 def __delitem__(self, key: str) -> None:427 """428 Remove the header `key`.429 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 430why, one step back430 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 431–440why, one step back431432 pop_indexes = []433 for idx, (item_key, item_value) in enumerate(self._list):434 if item_key == del_key:435 pop_indexes.append(idx)436437 for idx in reversed(pop_indexes):438 del self._list[idx]439440 def __contains__(self, key: typing.Any) -> bool:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 441why, one step back441 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 442–459why, one step back442 for header_key, header_value in self._list:443 if header_key == get_header_key:444 return True445 return False446447 def __iter__(self) -> typing.Iterator[typing.Any]:448 return iter(self.keys())449450 def __len__(self) -> int:451 return len(self._list)452453 def __eq__(self, other: typing.Any) -> bool:454 if not isinstance(other, Headers):455 return False456 return sorted(self._list) == sorted(other._list)457458 def __repr__(self) -> str:459 class_name = self.__class__.__name__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 460–464why, one step back460461 encoding_str = ""462 if self.encoding != "ascii":463 encoding_str = f", encoding={self.encoding!r}"464Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 465–466why, one step back465 as_dict = dict(self.items())466 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 467–469why, one step back467 return f"{class_name}({as_dict!r}{encoding_str})"468 as_list = self.items()469 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 470–477why, one step back470471472class Request:473 def __init__(474 self,475 method: str,476 url: typing.Union[str, URL],477 *,Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 478why, one step back478 data: RequestData = b"",Add json interfacesTom Christiebefore adoption5a63d31
line 479why, one step back479 json: typing.Any = None,query_params -> paramsTom Christiebefore adoptionbb70377
line 480why, one step back480 params: QueryParamTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 481why, one step back481 headers: HeaderTypes = None,Cookie support (#73)Tom Christiebefore adoptionfeae0a8
line 482why, one step back482 cookies: CookieTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 483–484why, one step back483 ):484 self.method = method.upper()query_params -> paramsTom Christiebefore adoptionbb70377
line 485why, one step back485 self.url = URL(url, params=params)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 486why, one step back486 self.headers = Headers(headers)Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 487–489why, one step back487 if cookies:488 self._cookies = Cookies(cookies)489 self._cookies.set_cookie_header(self)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 490why, one step back490Add json interfacesTom Christiebefore adoption5a63d31
lines 491–494why, one step back491 if json is not None:492 data = jsonlib.dumps(json).encode("utf-8")493 self.headers["Content-Type"] = "application/json"494Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 495why, one step back495 if isinstance(data, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 496why, one step back496 self.is_streaming = FalseMerge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
lines 497–501why, one step back497 self.content = data498 elif isinstance(data, dict):499 self.is_streaming = False500 self.content = urlencode(data, doseq=True).encode("utf-8")501 self.headers["Content-Type"] = "application/x-www-form-urlencoded"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 502–503why, one step back502 else:503 self.is_streaming = TrueMerge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 504why, one step back504 self.content_aiter = dataMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 505–509why, one step back505506 async def read(self) -> bytes:507 """508 Read and return the response content.509 """Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 510why, one step back510 if not hasattr(self, "content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 511why, one step back511 self.content = b"".join([part async for part in self.stream()])Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 512why, one step back512 return self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 513–515why, one step back513514 async def stream(self) -> typing.AsyncIterator[bytes]:515 if self.is_streaming:Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 516why, one step back516 async for part in self.content_aiter:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 517why, one step back517 yield partPrefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 518–519why, one step back518 elif self.content:519 yield self.contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 520–521why, one step back520521 def prepare(self) -> None:Response.contentTom Christiebefore adoption4c55113
lines 522–528why, one step back522 """523 Adds in any default headers. When using the `Client`, this will524 end up being called into by the `prepare_request()` stage.525526 You can omit this behavior by calling `Client.send()` with an527 explicitly built `Request` instance.528 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 529–536why, one step back529 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]530531 has_host = "host" in self.headers532 has_content_length = (533 "content-length" in self.headers or "transfer-encoding" in self.headers534 )535 has_accept_encoding = "accept-encoding" in self.headers536Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 537–538why, one step back537 if not has_host and self.url.authority:538 auto_headers.append((b"host", self.url.authority.encode("ascii")))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 539–541why, one step back539 if not has_content_length:540 if self.is_streaming:541 auto_headers.append((b"transfer-encoding", b"chunked"))Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
lines 542–543why, one step back542 elif self.content:543 content_length = str(len(self.content)).encode()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 544–550why, one step back544 auto_headers.append((b"content-length", content_length))545 if not has_accept_encoding:546 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))547548 for item in reversed(auto_headers):549 self.headers.raw.insert(0, item)550Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 551–556why, one step back551 @property552 def cookies(self) -> "Cookies":553 if not hasattr(self, "_cookies"):554 self._cookies = Cookies()555 return self._cookies556Still truckin' onTom Christiebefore adoption6cb5c0d
lines 557–559why, one step back557 def __repr__(self) -> str:558 class_name = self.__class__.__name__559 url = str(self.url)Improve class __repr__Tom Christiebefore adoption666d5a8
line 560why, one step back560 return f"<{class_name}({self.method!r}, {url!r})>"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 561why, one step back561Still truckin' onTom Christiebefore adoption6cb5c0d
line 562why, one step back562Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 563–567why, one step back563class Response:564 def __init__(565 self,566 status_code: int,567 *,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 568–570why, one step back568 reason_phrase: str = None,569 protocol: str = None,570 headers: HeaderTypes = None,Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 571why, one step back571 content: ResponseContent = b"",Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 572–575why, one step back572 on_close: typing.Callable = None,573 request: Request = None,574 history: typing.List["Response"] = None,575 ):Status code tweaks (#77)Tom Christiebefore adoptionc12c271
lines 576–577why, one step back576 self.status_code = StatusCode.enum_or_int(status_code)577 self.reason_phrase = StatusCode.get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 578–580why, one step back578 self.protocol = protocol579 self.headers = Headers(headers)580Response.contentTom Christiebefore adoption4c55113
line 581why, one step back581 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 582why, one step back582 self.is_closed = TrueResponse.contentTom Christiebefore adoption4c55113
lines 583–584why, one step back583 self.is_stream_consumed = True584 self._raw_content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 585why, one step back585 else:Response.contentTom Christiebefore adoption4c55113
lines 586–588why, one step back586 self.is_closed = False587 self.is_stream_consumed = False588 self._raw_stream = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 589why, one step back589Response.contentTom Christiebefore adoption4c55113
line 590why, one step back590 self.on_close = on_closeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 591–592why, one step back591 self.request = request592 self.history = [] if history is None else list(history)response.next()Tom Christiebefore adoptiond652479
line 593why, one step back593 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 594–596why, one step back594595 @property596 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 597–601why, one step back597 """598 Returns the URL for which the request was made.599600 Requires that `request` was provided when instantiating the response.601 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 602why, one step back602 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 603–604why, one step back603604 @propertyResponse.contentTom Christiebefore adoption4c55113
lines 605–607why, one step back605 def content(self) -> bytes:606 if not hasattr(self, "_content"):607 if hasattr(self, "_raw_content"):Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 608–610why, one step back608 content = self.decoder.decode(self._raw_content)609 content += self.decoder.flush()610 self._content = contentResponse.contentTom Christiebefore adoption4c55113
lines 611–613why, one step back611 else:612 raise ResponseNotRead()613 return self._contentAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 614–649why, one step back614615 @property616 def text(self) -> str:617 if not hasattr(self, "_text"):618 content = self.content619 if not content:620 self._text = ""621 else:622 encoding = self.encoding623 self._text = content.decode(encoding, errors="replace")624 return self._text625626 @property627 def encoding(self) -> str:628 if not hasattr(self, "_encoding"):629 encoding = self.charset_encoding630 if encoding is None or not is_known_encoding(encoding):631 encoding = self.apparent_encoding632 if encoding is None or not is_known_encoding(encoding):633 encoding = "utf-8"634 self._encoding = encoding635 return self._encoding636637 @encoding.setter638 def encoding(self, value: str) -> None:639 self._encoding = value640641 @property642 def charset_encoding(self) -> typing.Optional[str]:643 """644 Return the encoding, as specified by the Content-Type header.645 """646 content_type = self.headers.get("Content-Type")647 if content_type is None:648 return None649Truckin' onTom Christiebefore adoption0ca1c84
lines 650–654why, one step back650 parsed = cgi.parse_header(content_type)651 media_type, params = parsed[0], parsed[-1]652 if "charset" in params:653 return params["charset"].strip("'\"")654Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 655–657why, one step back655 # RFC 2616 specifies that 'iso-8859-1' should be used as the default656 # for 'text/*' media types, if no charset is provided.657 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1Truckin' onTom Christiebefore adoption0ca1c84
lines 658–661why, one step back658 if media_type.startswith("text/"):659 return "iso-8859-1"660661 return NoneAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 662–668why, one step back662663 @property664 def apparent_encoding(self) -> typing.Optional[str]:665 """666 Return the encoding, as it appears to autodetection.667 """668 return chardet.detect(self.content)["encoding"]Response.contentTom Christiebefore adoption4c55113
lines 669–670why, one step back669670 @propertyClean up response interfaceTom Christiebefore adoption4d908d0
lines 671–677why, one step back671 def decoder(self) -> Decoder:672 """673 Returns a decoder instance which can be used to decode the raw byte674 content, depending on the Content-Encoding used in the response.675 """676 if not hasattr(self, "_decoder"):677 decoders = [] # type: typing.List[Decoder]Response.contentTom Christiebefore adoption4c55113
line 678why, one step back678 values = self.headers.getlist("content-encoding", split_commas=True)Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 679–681why, one step back679 for value in values:680 value = value.strip().lower()681 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 682–691why, one step back682 decoders.append(decoder_cls())683684 if len(decoders) == 1:685 self._decoder = decoders[0]686 elif len(decoders) > 1:687 self._decoder = MultiDecoder(decoders)688 else:689 self._decoder = IdentityDecoder()690691 return self._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 692–696why, one step back692693 async def read(self) -> bytes:694 """695 Read and return the response content.696 """Response.contentTom Christiebefore adoption4c55113
line 697why, one step back697 if not hasattr(self, "_content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 698why, one step back698 self._content = b"".join([part async for part in self.stream()])Response.contentTom Christiebefore adoption4c55113
line 699why, one step back699 return self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 700–705why, one step back700701 async def stream(self) -> typing.AsyncIterator[bytes]:702 """703 A byte-iterator over the decoded response content.704 This allows us to handle gzip, deflate, and brotli encoded responses.705 """Response.contentTom Christiebefore adoption4c55113
lines 706–707why, one step back706 if hasattr(self, "_content"):707 yield self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 708–716why, one step back708 else:709 async for chunk in self.raw():710 yield self.decoder.decode(chunk)711 yield self.decoder.flush()712713 async def raw(self) -> typing.AsyncIterator[bytes]:714 """715 A byte-iterator over the raw response content.716 """Response.contentTom Christiebefore adoption4c55113
lines 717–728why, one step back717 if hasattr(self, "_raw_content"):718 yield self._raw_content719 else:720 if self.is_stream_consumed:721 raise StreamConsumed()722 if self.is_closed:723 raise ResponseClosed()724725 self.is_stream_consumed = True726 async for part in self._raw_stream:727 yield part728 await self.close()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 729–741why, one step back729730 async def close(self) -> None:731 """732 Close the response and release the connection.733 Automatically called if the response body is read to completion.734 """735 if not self.is_closed:736 self.is_closed = True737 if self.on_close is not None:738 await self.on_close()739740 @property741 def is_redirect(self) -> bool:Status code tweaks (#77)Tom Christiebefore adoptionc12c271
line 742why, one step back742 return StatusCode.is_redirect(self.status_code) and "location" in self.headersStill truckin' onTom Christiebefore adoption6cb5c0d
line 743why, one step back743Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 744–752why, one step back744 def raise_for_status(self) -> None:745 """746 Raise the `HttpError` if one occurred.747 """748 message = (749 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"750 "For more information check: https://httpstatuses.com/{0.status_code}"751 )752Status code tweaks (#77)Tom Christiebefore adoptionc12c271
line 753why, one step back753 if StatusCode.is_client_error(self.status_code):Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
line 754why, one step back754 message = message.format(self, error_type="Client Error")Status code tweaks (#77)Tom Christiebefore adoptionc12c271
line 755why, one step back755 elif StatusCode.is_server_error(self.status_code):Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 756–761why, one step back756 message = message.format(self, error_type="Server Error")757 else:758 message = ""759760 if message:761 raise HttpError(message)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 762why, one step back762Add response.json()Tom Christiebefore adoption2116d44
line 763why, one step back763 def json(self) -> typing.Any:Add json interfacesTom Christiebefore adoption5a63d31
line 764why, one step back764 return jsonlib.loads(self.content.decode("utf-8"))Add response.json()Tom Christiebefore adoption2116d44
line 765why, one step back765Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 766–773why, one step back766 @property767 def cookies(self) -> "Cookies":768 if not hasattr(self, "_cookies"):769 assert self.request is not None770 self._cookies = Cookies()771 self._cookies.extract_cookies(self)772 return self._cookies773Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 774why, one step back774 def __repr__(self) -> str:repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
line 775why, one step back775 return f"<Response({self.status_code}, {self.reason_phrase!r})>"Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 776–829why, one step back776777778class SyncResponse:779 """780 A thread-synchronous response. This class proxies onto a `Response`781 instance, providing standard synchronous interfaces where required.782 """783784 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):785 self._response = response786 self._loop = loop787788 @property789 def status_code(self) -> int:790 return self._response.status_code791792 @property793 def reason_phrase(self) -> str:794 return self._response.reason_phrase795796 @property797 def protocol(self) -> typing.Optional[str]:798 return self._response.protocol799800 @property801 def url(self) -> typing.Optional[URL]:802 return self._response.url803804 @property805 def request(self) -> typing.Optional[Request]:806 return self._response.request807808 @property809 def headers(self) -> Headers:810 return self._response.headers811812 @property813 def content(self) -> bytes:814 return self._response.content815816 @property817 def text(self) -> str:818 return self._response.text819820 @property821 def encoding(self) -> str:822 return self._response.encoding823824 @property825 def is_redirect(self) -> bool:826 return self._response.is_redirect827828 def raise_for_status(self) -> None:829 return self._response.raise_for_status()Add response.json()Tom Christiebefore adoption2116d44
lines 830–832why, one step back830831 def json(self) -> typing.Any:832 return self._response.json()Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 833–841why, one step back833834 def read(self) -> bytes:835 return self._loop.run_until_complete(self._response.read())836837 def stream(self) -> typing.Iterator[bytes]:838 inner = self._response.stream()839 while True:840 try:841 yield self._loop.run_until_complete(inner.__anext__())Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e
line 842why, one step back842 except StopAsyncIteration:Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 843–849why, one step back843 break844845 def raw(self) -> typing.Iterator[bytes]:846 inner = self._response.raw()847 while True:848 try:849 yield self._loop.run_until_complete(inner.__anext__())Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e
line 850why, one step back850 except StopAsyncIteration:Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 851–854why, one step back851 break852853 def close(self) -> None:854 return self._loop.run_until_complete(self._response.close())Merge pull request #56 from yeraydiazdiaz/test-additional-http-methodsTom Christiebefore adoption87cab4c
line 855why, one step back855Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 856–859why, one step back856 @property857 def cookies(self) -> "Cookies":858 return self._response.cookies859Merge pull request #56 from yeraydiazdiaz/test-additional-http-methodsTom Christiebefore adoption87cab4c
line 860why, one step back860 def __repr__(self) -> str:repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
line 861why, one step back861 return f"<Response({self.status_code}, {self.reason_phrase!r})>"Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 862–976why, one step back862863864class Cookies(MutableMapping):865 """866 HTTP Cookies, as a mutable mapping.867 """868869 def __init__(self, cookies: CookieTypes = None) -> None:870 if cookies is None or isinstance(cookies, dict):871 self.jar = CookieJar()872 if isinstance(cookies, dict):873 for key, value in cookies.items():874 self.set(key, value)875 elif isinstance(cookies, Cookies):876 self.jar = CookieJar()877 for cookie in cookies.jar:878 self.jar.set_cookie(cookie)879 else:880 self.jar = cookies881882 def extract_cookies(self, response: Response) -> None:883 """884 Loads any cookies based on the response `Set-Cookie` headers.885 """886 assert response.request is not None887 urlib_response = self._CookieCompatResponse(response)888 urllib_request = self._CookieCompatRequest(response.request)889890 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore891892 def set_cookie_header(self, request: Request) -> None:893 """894 Sets an appropriate 'Cookie:' HTTP header on the `Request`.895 """896 urllib_request = self._CookieCompatRequest(request)897 self.jar.add_cookie_header(urllib_request)898899 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:900 """901 Set a cookie value by name. May optionally include domain and path.902 """903 kwargs = dict(904 version=0,905 name=name,906 value=value,907 port=None,908 port_specified=False,909 domain=domain,910 domain_specified=bool(domain),911 domain_initial_dot=domain.startswith("."),912 path=path,913 path_specified=bool(path),914 secure=False,915 expires=None,916 discard=True,917 comment=None,918 comment_url=None,919 rest={"HttpOnly": None},920 rfc2109=False,921 )922 cookie = Cookie(**kwargs) # type: ignore923 self.jar.set_cookie(cookie)924925 def get( # type: ignore926 self, name: str, default: str = None, domain: str = None, path: str = None927 ) -> typing.Optional[str]:928 """929 Get a cookie by name. May optionally include domain and path930 in order to specify exactly which cookie to retrieve.931 """932 value = None933 for cookie in self.jar:934 if cookie.name == name:935 if domain is None or cookie.domain == domain: # type: ignore936 if path is None or cookie.path == path:937 if value is not None:938 message = f"Multiple cookies exist with name={name}"939 raise CookieConflict(message)940 value = cookie.value941942 if value is None:943 return default944 return value945946 def delete(self, name: str, domain: str = None, path: str = None) -> None:947 """948 Delete a cookie by name. May optionally include domain and path949 in order to specify exactly which cookie to delete.950 """951 if domain is not None and path is not None:952 return self.jar.clear(domain, path, name)953954 remove = []955 for cookie in self.jar:956 if cookie.name == name:957 if domain is None or cookie.domain == domain: # type: ignore958 if path is None or cookie.path == path:959 remove.append(cookie)960961 for cookie in remove:962 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore963964 def clear(self, domain: str = None, path: str = None) -> None:965 """966 Delete all cookies. Optionally include a domain and path in967 order to only delete a subset of all the cookies.968 """969 args = []970 if domain is not None:971 args.append(domain)972 if path is not None:973 assert domain is not None974 args.append(path)975 self.jar.clear(*args)976query_params -> paramsTom Christiebefore adoptionbb70377
line 977why, one step back977 def update(self, cookies: CookieTypes = None) -> None: # type: ignoreCookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 978–1036why, one step back978 cookies = Cookies(cookies)979 for cookie in cookies.jar:980 self.jar.set_cookie(cookie)981982 def __setitem__(self, name: str, value: str) -> None:983 return self.set(name, value)984985 def __getitem__(self, name: str) -> str:986 value = self.get(name)987 if value is None:988 raise KeyError(name)989 return value990991 def __delitem__(self, name: str) -> None:992 return self.delete(name)993994 def __len__(self) -> int:995 return len(self.jar)996997 def __iter__(self) -> typing.Iterator[str]:998 return (cookie.name for cookie in self.jar)9991000 def __bool__(self) -> bool:1001 for cookie in self.jar:1002 return True1003 return False10041005 class _CookieCompatRequest(urllib.request.Request):1006 """1007 Wraps a `Request` instance up in a compatability interface suitable1008 for use with `CookieJar` operations.1009 """10101011 def __init__(self, request: Request) -> None:1012 super().__init__(1013 url=str(request.url),1014 headers=dict(request.headers),1015 method=request.method,1016 )1017 self.request = request10181019 def add_unredirected_header(self, key: str, value: str) -> None:1020 super().add_unredirected_header(key, value)1021 self.request.headers[key] = value10221023 class _CookieCompatResponse:1024 """1025 Wraps a `Request` instance up in a compatability interface suitable1026 for use with `CookieJar` operations.1027 """10281029 def __init__(self, response: Response):1030 self.response = response10311032 def info(self) -> email.message.Message:1033 info = email.message.Message()1034 for key, value in self.response.headers.items():1035 info[key] = value1036 return info