models.py
This file
Path
httpcore/models.py
1,050 lines · 32.5 KiB · Python
Last changed by
Add response.json()Tom Christiebefore adoption2116d44
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 response.json()Tom Christiebefore adoption2116d44
line 4why, one step back4import jsonMerge 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)Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369
line 29why, one step back29from .status_codes import codesAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 30–35why, one step back30from .utils import (31 get_reason_phrase,32 is_known_encoding,33 normalize_header_key,34 normalize_header_value,35)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 36why, one step back36Finessing interfaceTom Christiebefore adoptiond7619a9
line 37why, one step back37URLTypes = typing.Union["URL", str]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 38why, one step back38Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 39–45why, one step back39QueryParamTypes = typing.Union[40 "QueryParams",41 typing.Mapping[str, str],42 typing.List[typing.Tuple[typing.Any, typing.Any]],43 str,44]45Finessing interfaceTom Christiebefore adoptiond7619a9
lines 46–51why, one step back46HeaderTypes = typing.Union[47 "Headers",48 typing.Dict[typing.AnyStr, typing.AnyStr],49 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],50]51Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 52–53why, one step back52CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]53Auth (#65)Tom Christiebefore adoption5afa7dd
lines 54–55why, one step back54AuthTypes = typing.Union[55 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 56why, one step back56 typing.Callable[["Request"], "Request"],Auth (#65)Tom Christiebefore adoption5afa7dd
lines 57–58why, one step back57]58Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 59why, one step back59RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 60why, one step back60Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 61why, one step back61ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]Finessing interfaceTom Christiebefore adoptiond7619a9
line 62why, one step back62Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 63why, one step back63Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 64why, one step back64class URL:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 65–68why, one step back65 def __init__(66 self,67 url: URLTypes,68 allow_relative: bool = False,query_params -> paramsTom Christiebefore adoptionbb70377
line 69why, one step back69 params: QueryParamTypes = None,Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 70why, one step back70 ) -> None:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 71why, one step back71 if isinstance(url, rfc3986.uri.URIReference):Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 72why, one step back72 self.components = urlAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 73–74why, one step back73 elif isinstance(url, str):74 self.components = rfc3986.api.uri_reference(url)Finessing interfaceTom Christiebefore adoptiond7619a9
lines 75–77why, one step back75 else:76 self.components = url.components77Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 78–83why, one step back78 # Handle IDNA domain names.79 if self.components.authority:80 idna_authority = self.components.authority.encode("idna").decode("ascii")81 if idna_authority != self.components.authority:82 self.components = self.components.copy_with(authority=idna_authority)83Fix docstringsTom Christiebefore adoption8a227c1
line 84why, one step back84 # Normalize scheme and domain name.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 85–86why, one step back85 self.components = self.components.normalize()86Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 87why, one step back87 # Add any query parameters.query_params -> paramsTom Christiebefore adoptionbb70377
lines 88–89why, one step back88 if params:89 query_string = str(QueryParams(params))Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 90–91why, one step back90 self.components = self.components.copy_with(query=query_string)91Add idna support. More tests.Tom Christiebefore adoptionb948798
line 92why, one step back92 # Enforce absolute URLs by default.Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 93–98why, one step back93 if not allow_relative:94 if not self.scheme:95 raise InvalidURL("No scheme included in URL.")96 if self.scheme not in ("http", "https"):97 raise InvalidURL('URL scheme must be "http" or "https".')98 if not self.host:Add idna support. More tests.Tom Christiebefore adoptionb948798
line 99why, one step back99 raise InvalidURL("No host included in URL.")Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 100–102why, one step back100101 @property102 def scheme(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 103why, one step back103 return self.components.scheme or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 104–105why, one step back104105 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 106–107why, one step back106 def authority(self) -> str:107 return self.components.authority or ""Auth (#65)Tom Christiebefore adoption5afa7dd
lines 108–111why, one step back108109 @property110 def username(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(":")[0]Auth (#65)Tom Christiebefore adoption5afa7dd
lines 113–116why, one step back113114 @property115 def password(self) -> str:116 userinfo = self.components.userinfo or ""Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 117why, one step back117 return userinfo.partition(":")[2]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 118–119why, one step back118119 @propertyUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 120–121why, one step back120 def host(self) -> str:121 return self.components.host or ""Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 122–127why, one step back122123 @property124 def port(self) -> int:125 port = self.components.port126 if port is None:127 return {"https": 443, "http": 80}[self.scheme]Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 128why, one step back128 return int(port)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 129–130why, one step back129130 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 131–138why, one step back131 def path(self) -> str:132 return self.components.path or "/"133134 @property135 def query(self) -> str:136 return self.components.query or ""137138 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 139why, one step back139 def full_path(self) -> str:Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
lines 140–142why, one step back140 path = self.path141 if self.query:142 path += "?" + self.queryMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 143–145why, one step back143 return path144145 @propertyMedia types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 146–149why, one step back146 def fragment(self) -> str:147 return self.components.fragment or ""148149 @propertyCarefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 150why, one step back150 def is_ssl(self) -> bool:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 151–153why, one step back151 return self.components.scheme == "https"152153 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 154–163why, one step back154 def is_absolute_url(self) -> bool:155 """156 Return `True` for absolute URLs such as 'http://example.com/path',157 and `False` for relative URLs such as '/path'.158 """159 # We don't use rfc3986's `is_absolute` because it treats160 # URLs with a fragment portion as not absolute.161 # What we actually care about is if the URL provides162 # a scheme and hostname to which connections should be made.163 return self.components.scheme and self.components.hostUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 164–165why, one step back164165 @propertyAdd idna support. More tests.Tom Christiebefore adoptionb948798
lines 166–169why, one step back166 def is_relative_url(self) -> bool:167 return not self.is_absolute_url168169 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 170–172why, one step back170 def origin(self) -> "Origin":171 return Origin(self)172Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 173–176why, one step back173 def copy_with(self, **kwargs: typing.Any) -> "URL":174 return URL(self.components.copy_with(**kwargs))175176 def resolve_with(self, base_url: URLTypes) -> "URL":Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 177–180why, one step back177 """178 Return an absolute URL, using base_url as the base.179 """180 # We drop any fragment portion, because RFC 3986 strictlyFix docstringsTom Christiebefore adoption8a227c1
line 181why, one step back181 # treats URLs with a fragment portion as not being absolute URLs.Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 182–183why, one step back182 base_url = URL(base_url).copy_with(fragment=None)183 return URL(self.components.resolve_with(base_url.components))Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 184why, one step back184Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 185–191why, one step back185 def __hash__(self) -> int:186 return hash(str(self))187188 def __eq__(self, other: typing.Any) -> bool:189 return isinstance(other, URL) and str(self) == str(other)190191 def __str__(self) -> str:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 192why, one step back192 return self.components.unsplit()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 193–200why, one step back193194 def __repr__(self) -> str:195 class_name = self.__class__.__name__196 url_str = str(self)197 return f"{class_name}({url_str!r})"198199200class Origin:Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 201–204why, one step back201 """202 The URL scheme and authority information, as a comparable, hashable object.203 """204Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
lines 205–206why, one step back205 def __init__(self, url: URLTypes) -> None:206 if not isinstance(url, URL):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 207why, one step back207 url = URL(url)Carefulness with encoding everywhereTom Christiebefore adoptione1ecb36
line 208why, one step back208 self.is_ssl = url.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 209why, one step back209 self.host = url.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 210–215why, one step back210 self.port = url.port211212 def __eq__(self, other: typing.Any) -> bool:213 return (214 isinstance(other, self.__class__)215 and self.is_ssl == other.is_sslUse rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 216why, one step back216 and self.host == other.hostMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 217–220why, one step back217 and self.port == other.port218 )219220 def __hash__(self) -> int:Use rfc3986 for URL handlingTom Christiebefore adoption302fe93
line 221why, one step back221 return hash((self.is_ssl, self.host, self.port))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 222–223why, one step back222223Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 224why, one step back224class QueryParams(typing.Mapping[str, str]):Improve class __repr__Tom Christiebefore adoption666d5a8
lines 225–228why, one step back225 """226 URL query parameters, as a multi-dict.227 """228Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 229–292why, one step back229 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:230 assert len(args) < 2, "Too many arguments."231 assert not (args and kwargs), "Cannot mix named and unnamed arguments."232233 value = args[0] if args else kwargs234235 if isinstance(value, str):236 items = parse_qsl(value)237 elif isinstance(value, QueryParams):238 items = value.multi_items()239 elif isinstance(value, list):240 items = value241 else:242 items = value.items() # type: ignore243244 self._list = [(str(k), str(v)) for k, v in items]245 self._dict = {str(k): str(v) for k, v in items}246247 def getlist(self, key: typing.Any) -> typing.List[str]:248 return [item_value for item_key, item_value in self._list if item_key == key]249250 def keys(self) -> typing.KeysView:251 return self._dict.keys()252253 def values(self) -> typing.ValuesView:254 return self._dict.values()255256 def items(self) -> typing.ItemsView:257 return self._dict.items()258259 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:260 return list(self._list)261262 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:263 if key in self._dict:264 return self._dict[key]265 return default266267 def __getitem__(self, key: typing.Any) -> str:268 return self._dict[key]269270 def __contains__(self, key: typing.Any) -> bool:271 return key in self._dict272273 def __iter__(self) -> typing.Iterator[typing.Any]:274 return iter(self.keys())275276 def __len__(self) -> int:277 return len(self._dict)278279 def __eq__(self, other: typing.Any) -> bool:280 if not isinstance(other, self.__class__):281 return False282 return sorted(self._list) == sorted(other._list)283284 def __str__(self) -> str:285 return urlencode(self._list)286287 def __repr__(self) -> str:288 class_name = self.__class__.__name__289 query_string = str(self)290 return f"{class_name}({query_string!r})"291292Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 293–294why, one step back293class Headers(typing.MutableMapping[str, str]):294 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
line 295why, one step back295 HTTP headers, as a case-insensitive multi-dict.Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 296–297why, one step back296 """297Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 298why, one step back298 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 299–304why, one step back299 if headers is None:300 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]301 elif isinstance(headers, Headers):302 self._list = list(headers.raw)303 elif isinstance(headers, dict):304 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 305why, one step back305 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 306–309why, one step back306 for k, v in headers.items()307 ]308 else:309 self._list = [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 310–311why, one step back310 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))311 for k, v in headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 312why, one step back312 ]Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 313why, one step back313 self._encoding = encodingMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 314–315why, one step back314315 @propertyRejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 316–317why, one step back316 def encoding(self) -> str:317 """Merge pull request #42 from encode/query-paramsTom Christiebefore adoption3de0425
lines 318–319why, one step back318 Header encoding is mandated as ascii, but we allow fallbacks to utf-8319 or iso-8859-1.Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 320–344why, one step back320 """321 if self._encoding is None:322 for encoding in ["ascii", "utf-8"]:323 for key, value in self.raw:324 try:325 key.decode(encoding)326 value.decode(encoding)327 except UnicodeDecodeError:328 break329 else:330 # The else block runs if 'break' did not occur, meaning331 # all values fitted the encoding.332 self._encoding = encoding333 break334 else:335 # The ISO-8859-1 encoding covers all 256 code points in a byte,336 # so will never raise decode errors.337 self._encoding = "iso-8859-1"338 return self._encoding339340 @encoding.setter341 def encoding(self, value: str) -> None:342 self._encoding = value343344 @propertyMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 345why, one step back345 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 346–349why, one step back346 """347 Returns a list of the raw header items, as byte pairs.348 May be mutated in-place.349 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 350–352why, one step back350 return self._list351352 def keys(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 353why, one step back353 return [key.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 354–355why, one step back354355 def values(self) -> typing.List[str]: # type: ignoreRejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 356why, one step back356 return [value.decode(self.encoding) for key, value in self._list]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 357–359why, one step back357358 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore359 return [Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 360why, one step back360 (key.decode(self.encoding), value.decode(self.encoding))Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 361–369why, one step back361 for key, value in self._list362 ]363364 def get(self, key: str, default: typing.Any = None) -> typing.Any:365 try:366 return self[key]367 except KeyError:368 return default369Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 370why, one step back370 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 371–377why, one step back371 """372 Return multiple header values.373 """374 get_header_key = key.lower().encode(self.encoding)375376 values = [377 item_value.decode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 378–381why, one step back378 for item_key, item_value in self._list379 if item_key == get_header_key380 ]381Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 382–389why, one step back382 if not split_commas:383 return values384385 split_values = []386 for value in values:387 split_values.extend([item.strip() for item in value.split(",")])388 return split_values389Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 390why, one step back390 def __getitem__(self, key: str) -> str:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 391–399why, one step back391 """392 Return a single header value.393394 If there are multiple headers with the same key, then we concatenate395 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2396 """397 normalized_key = key.lower().encode(self.encoding)398399 items = []Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 400why, one step back400 for header_key, header_value in self._list:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 401–406why, one step back401 if header_key == normalized_key:402 items.append(header_value.decode(self.encoding))403404 if items:405 return ", ".join(items)406Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 407–413why, one step back407 raise KeyError(key)408409 def __setitem__(self, key: str, value: str) -> None:410 """411 Set the header `key` to `value`, removing any duplicate entries.412 Retains insertion order.413 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 414–415why, one step back414 set_key = key.lower().encode(self.encoding)415 set_value = value.encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 416–434why, one step back416417 found_indexes = []418 for idx, (item_key, item_value) in enumerate(self._list):419 if item_key == set_key:420 found_indexes.append(idx)421422 for idx in reversed(found_indexes[1:]):423 del self._list[idx]424425 if found_indexes:426 idx = found_indexes[0]427 self._list[idx] = (set_key, set_value)428 else:429 self._list.append((set_key, set_value))430431 def __delitem__(self, key: str) -> None:432 """433 Remove the header `key`.434 """Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 435why, one step back435 del_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 436–445why, one step back436437 pop_indexes = []438 for idx, (item_key, item_value) in enumerate(self._list):439 if item_key == del_key:440 pop_indexes.append(idx)441442 for idx in reversed(pop_indexes):443 del self._list[idx]444445 def __contains__(self, key: typing.Any) -> bool:Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 446why, one step back446 get_header_key = key.lower().encode(self.encoding)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 447–464why, one step back447 for header_key, header_value in self._list:448 if header_key == get_header_key:449 return True450 return False451452 def __iter__(self) -> typing.Iterator[typing.Any]:453 return iter(self.keys())454455 def __len__(self) -> int:456 return len(self._list)457458 def __eq__(self, other: typing.Any) -> bool:459 if not isinstance(other, Headers):460 return False461 return sorted(self._list) == sorted(other._list)462463 def __repr__(self) -> str:464 class_name = self.__class__.__name__Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 465–469why, one step back465466 encoding_str = ""467 if self.encoding != "ascii":468 encoding_str = f", encoding={self.encoding!r}"469Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 470–471why, one step back470 as_dict = dict(self.items())471 if len(as_dict) == len(self):Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 472–474why, one step back472 return f"{class_name}({as_dict!r}{encoding_str})"473 as_list = self.items()474 return f"{class_name}({as_list!r}{encoding_str})"Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 475–482why, one step back475476477class Request:478 def __init__(479 self,480 method: str,481 url: typing.Union[str, URL],482 *,Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 483why, one step back483 data: RequestData = b"",query_params -> paramsTom Christiebefore adoptionbb70377
line 484why, one step back484 params: QueryParamTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 485why, one step back485 headers: HeaderTypes = None,Cookie support (#73)Tom Christiebefore adoptionfeae0a8
line 486why, one step back486 cookies: CookieTypes = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 487–488why, one step back487 ):488 self.method = method.upper()query_params -> paramsTom Christiebefore adoptionbb70377
line 489why, one step back489 self.url = URL(url, params=params)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
line 490why, one step back490 self.headers = Headers(headers)Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 491–493why, one step back491 if cookies:492 self._cookies = Cookies(cookies)493 self._cookies.set_cookie_header(self)Merge pull request #44 from encode/request-dataTom Christiebefore adoption39a5c53
lines 494–495why, one step back494495 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 ):Truckin' onTom Christiebefore adoption6b60d95
lines 576–577why, one step back576 try:577 # Use a StatusCode IntEnum if possible, for a nicer representation.Still truckin' onTom Christiebefore adoption6cb5c0d
line 578why, one step back578 self.status_code = codes(status_code) # type: intTruckin' onTom Christiebefore adoption6b60d95
lines 579–580why, one step back579 except ValueError:580 self.status_code = status_codeResponse.contentTom Christiebefore adoption4c55113
line 581why, one step back581 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 582–584why, one step back582 self.protocol = protocol583 self.headers = Headers(headers)584Response.contentTom Christiebefore adoption4c55113
line 585why, one step back585 if isinstance(content, bytes):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 586why, one step back586 self.is_closed = TrueResponse.contentTom Christiebefore adoption4c55113
lines 587–588why, one step back587 self.is_stream_consumed = True588 self._raw_content = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 589why, one step back589 else:Response.contentTom Christiebefore adoption4c55113
lines 590–592why, one step back590 self.is_closed = False591 self.is_stream_consumed = False592 self._raw_stream = contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 593why, one step back593Response.contentTom Christiebefore adoption4c55113
line 594why, one step back594 self.on_close = on_closeMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 595–596why, one step back595 self.request = request596 self.history = [] if history is None else list(history)response.next()Tom Christiebefore adoptiond652479
line 597why, one step back597 self.next = None # typing.Optional[typing.Callable]Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 598–600why, one step back598599 @property600 def url(self) -> typing.Optional[URL]:Clean up response interfaceTom Christiebefore adoption4d908d0
lines 601–605why, one step back601 """602 Returns the URL for which the request was made.603604 Requires that `request` was provided when instantiating the response.605 """Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 606why, one step back606 return None if self.request is None else self.request.urlClean up response interfaceTom Christiebefore adoption4d908d0
lines 607–608why, one step back607608 @propertyResponse.contentTom Christiebefore adoption4c55113
lines 609–611why, one step back609 def content(self) -> bytes:610 if not hasattr(self, "_content"):611 if hasattr(self, "_raw_content"):Add response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 612–614why, one step back612 content = self.decoder.decode(self._raw_content)613 content += self.decoder.flush()614 self._content = contentResponse.contentTom Christiebefore adoption4c55113
lines 615–617why, one step back615 else:616 raise ResponseNotRead()617 return self._contentAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 618–653why, one step back618619 @property620 def text(self) -> str:621 if not hasattr(self, "_text"):622 content = self.content623 if not content:624 self._text = ""625 else:626 encoding = self.encoding627 self._text = content.decode(encoding, errors="replace")628 return self._text629630 @property631 def encoding(self) -> str:632 if not hasattr(self, "_encoding"):633 encoding = self.charset_encoding634 if encoding is None or not is_known_encoding(encoding):635 encoding = self.apparent_encoding636 if encoding is None or not is_known_encoding(encoding):637 encoding = "utf-8"638 self._encoding = encoding639 return self._encoding640641 @encoding.setter642 def encoding(self, value: str) -> None:643 self._encoding = value644645 @property646 def charset_encoding(self) -> typing.Optional[str]:647 """648 Return the encoding, as specified by the Content-Type header.649 """650 content_type = self.headers.get("Content-Type")651 if content_type is None:652 return None653Truckin' onTom Christiebefore adoption0ca1c84
lines 654–658why, one step back654 parsed = cgi.parse_header(content_type)655 media_type, params = parsed[0], parsed[-1]656 if "charset" in params:657 return params["charset"].strip("'\"")658Media types with 'text/' should default to iso-8859-1Tom Christiebefore adoptiond7cf8bb
lines 659–661why, one step back659 # RFC 2616 specifies that 'iso-8859-1' should be used as the default660 # for 'text/*' media types, if no charset is provided.661 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1Truckin' onTom Christiebefore adoption0ca1c84
lines 662–665why, one step back662 if media_type.startswith("text/"):663 return "iso-8859-1"664665 return NoneAdd response.text and response.encodingTom Christiebefore adoptiond8df61b
lines 666–672why, one step back666667 @property668 def apparent_encoding(self) -> typing.Optional[str]:669 """670 Return the encoding, as it appears to autodetection.671 """672 return chardet.detect(self.content)["encoding"]Response.contentTom Christiebefore adoption4c55113
lines 673–674why, one step back673674 @propertyClean up response interfaceTom Christiebefore adoption4d908d0
lines 675–681why, one step back675 def decoder(self) -> Decoder:676 """677 Returns a decoder instance which can be used to decode the raw byte678 content, depending on the Content-Encoding used in the response.679 """680 if not hasattr(self, "_decoder"):681 decoders = [] # type: typing.List[Decoder]Response.contentTom Christiebefore adoption4c55113
line 682why, one step back682 values = self.headers.getlist("content-encoding", split_commas=True)Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 683–685why, one step back683 for value in values:684 value = value.strip().lower()685 decoder_cls = SUPPORTED_DECODERS[value]Clean up response interfaceTom Christiebefore adoption4d908d0
lines 686–695why, one step back686 decoders.append(decoder_cls())687688 if len(decoders) == 1:689 self._decoder = decoders[0]690 elif len(decoders) > 1:691 self._decoder = MultiDecoder(decoders)692 else:693 self._decoder = IdentityDecoder()694695 return self._decoderMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 696–700why, one step back696697 async def read(self) -> bytes:698 """699 Read and return the response content.700 """Response.contentTom Christiebefore adoption4c55113
line 701why, one step back701 if not hasattr(self, "_content"):Merge pull request #53 from yunstanford/patch-0Tom Christiebefore adoption21ac95a
line 702why, one step back702 self._content = b"".join([part async for part in self.stream()])Response.contentTom Christiebefore adoption4c55113
line 703why, one step back703 return self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 704–709why, one step back704705 async def stream(self) -> typing.AsyncIterator[bytes]:706 """707 A byte-iterator over the decoded response content.708 This allows us to handle gzip, deflate, and brotli encoded responses.709 """Response.contentTom Christiebefore adoption4c55113
lines 710–711why, one step back710 if hasattr(self, "_content"):711 yield self._contentMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 712–720why, one step back712 else:713 async for chunk in self.raw():714 yield self.decoder.decode(chunk)715 yield self.decoder.flush()716717 async def raw(self) -> typing.AsyncIterator[bytes]:718 """719 A byte-iterator over the raw response content.720 """Response.contentTom Christiebefore adoption4c55113
lines 721–732why, one step back721 if hasattr(self, "_raw_content"):722 yield self._raw_content723 else:724 if self.is_stream_consumed:725 raise StreamConsumed()726 if self.is_closed:727 raise ResponseClosed()728729 self.is_stream_consumed = True730 async for part in self._raw_stream:731 yield part732 await self.close()Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 733–746why, one step back733734 async def close(self) -> None:735 """736 Close the response and release the connection.737 Automatically called if the response body is read to completion.738 """739 if not self.is_closed:740 self.is_closed = True741 if self.on_close is not None:742 await self.on_close()743744 @property745 def is_redirect(self) -> bool:746 return (Finessing interfaceTom Christiebefore adoptiond7619a9
lines 747–748why, one step back747 self.status_code748 in (Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369
lines 749–753why, one step back749 codes.MOVED_PERMANENTLY,750 codes.FOUND,751 codes.SEE_OTHER,752 codes.TEMPORARY_REDIRECT,753 codes.PERMANENT_REDIRECT,Finessing interfaceTom Christiebefore adoptiond7619a9
lines 754–755why, one step back754 )755 and "location" in self.headersMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 756why, one step back756 )Still truckin' onTom Christiebefore adoption6cb5c0d
line 757why, one step back757Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 758–775why, one step back758 def raise_for_status(self) -> None:759 """760 Raise the `HttpError` if one occurred.761 """762 message = (763 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"764 "For more information check: https://httpstatuses.com/{0.status_code}"765 )766767 if 400 <= self.status_code < 500:768 message = message.format(self, error_type="Client Error")769 elif 500 <= self.status_code < 600:770 message = message.format(self, error_type="Server Error")771 else:772 message = ""773774 if message:775 raise HttpError(message)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 776why, one step back776Add response.json()Tom Christiebefore adoption2116d44
lines 777–779why, one step back777 def json(self) -> typing.Any:778 return json.loads(self.content.decode("utf-8"))779Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 780–787why, one step back780 @property781 def cookies(self) -> "Cookies":782 if not hasattr(self, "_cookies"):783 assert self.request is not None784 self._cookies = Cookies()785 self._cookies.extract_cookies(self)786 return self._cookies787Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 788why, one step back788 def __repr__(self) -> str:repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
line 789why, one step back789 return f"<Response({self.status_code}, {self.reason_phrase!r})>"Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 790–843why, one step back790791792class SyncResponse:793 """794 A thread-synchronous response. This class proxies onto a `Response`795 instance, providing standard synchronous interfaces where required.796 """797798 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):799 self._response = response800 self._loop = loop801802 @property803 def status_code(self) -> int:804 return self._response.status_code805806 @property807 def reason_phrase(self) -> str:808 return self._response.reason_phrase809810 @property811 def protocol(self) -> typing.Optional[str]:812 return self._response.protocol813814 @property815 def url(self) -> typing.Optional[URL]:816 return self._response.url817818 @property819 def request(self) -> typing.Optional[Request]:820 return self._response.request821822 @property823 def headers(self) -> Headers:824 return self._response.headers825826 @property827 def content(self) -> bytes:828 return self._response.content829830 @property831 def text(self) -> str:832 return self._response.text833834 @property835 def encoding(self) -> str:836 return self._response.encoding837838 @property839 def is_redirect(self) -> bool:840 return self._response.is_redirect841842 def raise_for_status(self) -> None:843 return self._response.raise_for_status()Add response.json()Tom Christiebefore adoption2116d44
lines 844–846why, one step back844845 def json(self) -> typing.Any:846 return self._response.json()Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 847–855why, one step back847848 def read(self) -> bytes:849 return self._loop.run_until_complete(self._response.read())850851 def stream(self) -> typing.Iterator[bytes]:852 inner = self._response.stream()853 while True:854 try:855 yield self._loop.run_until_complete(inner.__anext__())Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e
line 856why, one step back856 except StopAsyncIteration:Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 857–863why, one step back857 break858859 def raw(self) -> typing.Iterator[bytes]:860 inner = self._response.raw()861 while True:862 try:863 yield self._loop.run_until_complete(inner.__anext__())Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e
line 864why, one step back864 except StopAsyncIteration:Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 865–868why, one step back865 break866867 def close(self) -> None:868 return self._loop.run_until_complete(self._response.close())Merge pull request #56 from yeraydiazdiaz/test-additional-http-methodsTom Christiebefore adoption87cab4c
line 869why, one step back869Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 870–873why, one step back870 @property871 def cookies(self) -> "Cookies":872 return self._response.cookies873Merge pull request #56 from yeraydiazdiaz/test-additional-http-methodsTom Christiebefore adoption87cab4c
line 874why, one step back874 def __repr__(self) -> str:repr change: <SyncResponse ...> -> <Response ...>Tom Christiebefore adoption73d5fca
line 875why, one step back875 return f"<Response({self.status_code}, {self.reason_phrase!r})>"Cookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 876–990why, one step back876877878class Cookies(MutableMapping):879 """880 HTTP Cookies, as a mutable mapping.881 """882883 def __init__(self, cookies: CookieTypes = None) -> None:884 if cookies is None or isinstance(cookies, dict):885 self.jar = CookieJar()886 if isinstance(cookies, dict):887 for key, value in cookies.items():888 self.set(key, value)889 elif isinstance(cookies, Cookies):890 self.jar = CookieJar()891 for cookie in cookies.jar:892 self.jar.set_cookie(cookie)893 else:894 self.jar = cookies895896 def extract_cookies(self, response: Response) -> None:897 """898 Loads any cookies based on the response `Set-Cookie` headers.899 """900 assert response.request is not None901 urlib_response = self._CookieCompatResponse(response)902 urllib_request = self._CookieCompatRequest(response.request)903904 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore905906 def set_cookie_header(self, request: Request) -> None:907 """908 Sets an appropriate 'Cookie:' HTTP header on the `Request`.909 """910 urllib_request = self._CookieCompatRequest(request)911 self.jar.add_cookie_header(urllib_request)912913 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:914 """915 Set a cookie value by name. May optionally include domain and path.916 """917 kwargs = dict(918 version=0,919 name=name,920 value=value,921 port=None,922 port_specified=False,923 domain=domain,924 domain_specified=bool(domain),925 domain_initial_dot=domain.startswith("."),926 path=path,927 path_specified=bool(path),928 secure=False,929 expires=None,930 discard=True,931 comment=None,932 comment_url=None,933 rest={"HttpOnly": None},934 rfc2109=False,935 )936 cookie = Cookie(**kwargs) # type: ignore937 self.jar.set_cookie(cookie)938939 def get( # type: ignore940 self, name: str, default: str = None, domain: str = None, path: str = None941 ) -> typing.Optional[str]:942 """943 Get a cookie by name. May optionally include domain and path944 in order to specify exactly which cookie to retrieve.945 """946 value = None947 for cookie in self.jar:948 if cookie.name == name:949 if domain is None or cookie.domain == domain: # type: ignore950 if path is None or cookie.path == path:951 if value is not None:952 message = f"Multiple cookies exist with name={name}"953 raise CookieConflict(message)954 value = cookie.value955956 if value is None:957 return default958 return value959960 def delete(self, name: str, domain: str = None, path: str = None) -> None:961 """962 Delete a cookie by name. May optionally include domain and path963 in order to specify exactly which cookie to delete.964 """965 if domain is not None and path is not None:966 return self.jar.clear(domain, path, name)967968 remove = []969 for cookie in self.jar:970 if cookie.name == name:971 if domain is None or cookie.domain == domain: # type: ignore972 if path is None or cookie.path == path:973 remove.append(cookie)974975 for cookie in remove:976 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore977978 def clear(self, domain: str = None, path: str = None) -> None:979 """980 Delete all cookies. Optionally include a domain and path in981 order to only delete a subset of all the cookies.982 """983 args = []984 if domain is not None:985 args.append(domain)986 if path is not None:987 assert domain is not None988 args.append(path)989 self.jar.clear(*args)990query_params -> paramsTom Christiebefore adoptionbb70377
line 991why, one step back991 def update(self, cookies: CookieTypes = None) -> None: # type: ignoreCookie support (#73)Tom Christiebefore adoptionfeae0a8
lines 992–1050why, one step back992 cookies = Cookies(cookies)993 for cookie in cookies.jar:994 self.jar.set_cookie(cookie)995996 def __setitem__(self, name: str, value: str) -> None:997 return self.set(name, value)998999 def __getitem__(self, name: str) -> str:1000 value = self.get(name)1001 if value is None:1002 raise KeyError(name)1003 return value10041005 def __delitem__(self, name: str) -> None:1006 return self.delete(name)10071008 def __len__(self) -> int:1009 return len(self.jar)10101011 def __iter__(self) -> typing.Iterator[str]:1012 return (cookie.name for cookie in self.jar)10131014 def __bool__(self) -> bool:1015 for cookie in self.jar:1016 return True1017 return False10181019 class _CookieCompatRequest(urllib.request.Request):1020 """1021 Wraps a `Request` instance up in a compatability interface suitable1022 for use with `CookieJar` operations.1023 """10241025 def __init__(self, request: Request) -> None:1026 super().__init__(1027 url=str(request.url),1028 headers=dict(request.headers),1029 method=request.method,1030 )1031 self.request = request10321033 def add_unredirected_header(self, key: str, value: str) -> None:1034 super().add_unredirected_header(key, value)1035 self.request.headers[key] = value10361037 class _CookieCompatResponse:1038 """1039 Wraps a `Request` instance up in a compatability interface suitable1040 for use with `CookieJar` operations.1041 """10421043 def __init__(self, response: Response):1044 self.response = response10451046 def info(self) -> email.message.Message:1047 info = email.message.Message()1048 for key, value in self.response.headers.items():1049 info[key] = value1050 return info