models.py
This file
Path
http3/models.py
1,168 lines · 36.6 KiB · Python
Last changed by
Encoding detection in Response.json (#116)Yeray Diaz Diazbefore adoption5442006
History of this fileTake it
http3 (#86)Tom Christiebefore adoptionc9747aa
lines 1–12why, one step back1import cgi2import email.message3import json as jsonlib4import typing5import urllib.request6from collections.abc import MutableMapping7from http.cookiejar import Cookie, CookieJar8from urllib.parse import parse_qsl, urlencode910import chardet11import rfc398612Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
line 13why, one step back13from .config import USER_AGENThttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 14–28why, one step back14from .decoders import (15 ACCEPT_ENCODING,16 SUPPORTED_DECODERS,17 Decoder,18 IdentityDecoder,19 MultiDecoder,20)21from .exceptions import (22 CookieConflict,23 HttpError,24 InvalidURL,25 ResponseClosed,26 ResponseNotRead,27 StreamConsumed,28)Multipart support (#90)Tom Christiebefore adoption6a44b05
line 29why, one step back29from .multipart import multipart_encodehttp3 (#86)Tom Christiebefore adoptionc9747aa
line 30why, one step back30from .status_codes import StatusCodeEncoding detection in Response.json (#116)Yeray Diaz Diazbefore adoption5442006
lines 31–36why, one step back31from .utils import (32 guess_json_utf,33 is_known_encoding,34 normalize_header_key,35 normalize_header_value,36)http3 (#86)Tom Christiebefore adoptionc9747aa
lines 37–59why, one step back3738URLTypes = typing.Union["URL", str]3940QueryParamTypes = typing.Union[41 "QueryParams",42 typing.Mapping[str, str],43 typing.List[typing.Tuple[typing.Any, typing.Any]],44 str,45]4647HeaderTypes = typing.Union[48 "Headers",49 typing.Dict[typing.AnyStr, typing.AnyStr],50 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],51]5253CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]5455AuthTypes = typing.Union[56 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],57 typing.Callable[["AsyncRequest"], "AsyncRequest"],58]59Include host header directly (#109)Tom Christiebefore adoption5539b69
line 60why, one step back60AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]http3 (#86)Tom Christiebefore adoptionc9747aa
line 61why, one step back61Include host header directly (#109)Tom Christiebefore adoption5539b69
line 62why, one step back62RequestData = typing.Union[dict, str, bytes, typing.Iterator[bytes]]http3 (#86)Tom Christiebefore adoptionc9747aa
line 63why, one step back63Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 64–74why, one step back64RequestFiles = typing.Dict[65 str,66 typing.Union[67 typing.IO[typing.AnyStr], # file68 typing.Tuple[str, typing.IO[typing.AnyStr]], # (filename, file)69 typing.Tuple[70 str, typing.IO[typing.AnyStr], str71 ], # (filename, file, content_type)72 ],73]74http3 (#86)Tom Christiebefore adoptionc9747aa
lines 75–189why, one step back75AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]7677ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]787980class URL:81 def __init__(82 self,83 url: URLTypes,84 allow_relative: bool = False,85 params: QueryParamTypes = None,86 ) -> None:87 if isinstance(url, rfc3986.uri.URIReference):88 self.components = url89 elif isinstance(url, str):90 self.components = rfc3986.api.uri_reference(url)91 else:92 self.components = url.components9394 # Handle IDNA domain names.95 if self.components.authority:96 idna_authority = self.components.authority.encode("idna").decode("ascii")97 if idna_authority != self.components.authority:98 self.components = self.components.copy_with(authority=idna_authority)99100 # Normalize scheme and domain name.101 self.components = self.components.normalize()102103 # Add any query parameters.104 if params:105 query_string = str(QueryParams(params))106 self.components = self.components.copy_with(query=query_string)107108 # Enforce absolute URLs by default.109 if not allow_relative:110 if not self.scheme:111 raise InvalidURL("No scheme included in URL.")112 if not self.host:113 raise InvalidURL("No host included in URL.")114115 @property116 def scheme(self) -> str:117 return self.components.scheme or ""118119 @property120 def authority(self) -> str:121 return self.components.authority or ""122123 @property124 def username(self) -> str:125 userinfo = self.components.userinfo or ""126 return userinfo.partition(":")[0]127128 @property129 def password(self) -> str:130 userinfo = self.components.userinfo or ""131 return userinfo.partition(":")[2]132133 @property134 def host(self) -> str:135 return self.components.host or ""136137 @property138 def port(self) -> int:139 port = self.components.port140 if port is None:141 return {"https": 443, "http": 80}[self.scheme]142 return int(port)143144 @property145 def path(self) -> str:146 return self.components.path or "/"147148 @property149 def query(self) -> str:150 return self.components.query or ""151152 @property153 def full_path(self) -> str:154 path = self.path155 if self.query:156 path += "?" + self.query157 return path158159 @property160 def fragment(self) -> str:161 return self.components.fragment or ""162163 @property164 def is_ssl(self) -> bool:165 return self.components.scheme == "https"166167 @property168 def is_absolute_url(self) -> bool:169 """170 Return `True` for absolute URLs such as 'http://example.com/path',171 and `False` for relative URLs such as '/path'.172 """173 # We don't use rfc3986's `is_absolute` because it treats174 # URLs with a fragment portion as not absolute.175 # What we actually care about is if the URL provides176 # a scheme and hostname to which connections should be made.177 return self.components.scheme and self.components.host178179 @property180 def is_relative_url(self) -> bool:181 return not self.is_absolute_url182183 @property184 def origin(self) -> "Origin":185 return Origin(self)186187 def copy_with(self, **kwargs: typing.Any) -> "URL":188 return URL(self.components.copy_with(**kwargs))189Support Client(base_url=...)Tom Christiebefore adoption9d5aaff
line 190why, one step back190 def join(self, relative_url: URLTypes) -> "URL":http3 (#86)Tom Christiebefore adoptionc9747aa
line 191why, one step back191 """Support Client(base_url=...)Tom Christiebefore adoption9d5aaff
line 192why, one step back192 Return an absolute URL, using given this URL as the base.http3 (#86)Tom Christiebefore adoptionc9747aa
line 193why, one step back193 """Support Client(base_url=...)Tom Christiebefore adoption9d5aaff
lines 194–196why, one step back194 if self.is_relative_url:195 return URL(relative_url)196http3 (#86)Tom Christiebefore adoptionc9747aa
lines 197–198why, one step back197 # We drop any fragment portion, because RFC 3986 strictly198 # treats URLs with a fragment portion as not being absolute URLs.Support Client(base_url=...)Tom Christiebefore adoption9d5aaff
lines 199–201why, one step back199 base_components = self.components.copy_with(fragment=None)200 relative_url = URL(relative_url, allow_relative=True)201 return URL(relative_url.components.resolve_with(base_components))http3 (#86)Tom Christiebefore adoptionc9747aa
lines 202–511why, one step back202203 def __hash__(self) -> int:204 return hash(str(self))205206 def __eq__(self, other: typing.Any) -> bool:207 return isinstance(other, URL) and str(self) == str(other)208209 def __str__(self) -> str:210 return self.components.unsplit()211212 def __repr__(self) -> str:213 class_name = self.__class__.__name__214 url_str = str(self)215 return f"{class_name}({url_str!r})"216217218class Origin:219 """220 The URL scheme and authority information, as a comparable, hashable object.221 """222223 def __init__(self, url: URLTypes) -> None:224 if not isinstance(url, URL):225 url = URL(url)226 self.is_ssl = url.is_ssl227 self.host = url.host228 self.port = url.port229230 def __eq__(self, other: typing.Any) -> bool:231 return (232 isinstance(other, self.__class__)233 and self.is_ssl == other.is_ssl234 and self.host == other.host235 and self.port == other.port236 )237238 def __hash__(self) -> int:239 return hash((self.is_ssl, self.host, self.port))240241242class QueryParams(typing.Mapping[str, str]):243 """244 URL query parameters, as a multi-dict.245 """246247 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:248 assert len(args) < 2, "Too many arguments."249 assert not (args and kwargs), "Cannot mix named and unnamed arguments."250251 value = args[0] if args else kwargs252253 if isinstance(value, str):254 items = parse_qsl(value)255 elif isinstance(value, QueryParams):256 items = value.multi_items()257 elif isinstance(value, list):258 items = value259 else:260 items = value.items() # type: ignore261262 self._list = [(str(k), str(v)) for k, v in items]263 self._dict = {str(k): str(v) for k, v in items}264265 def getlist(self, key: typing.Any) -> typing.List[str]:266 return [item_value for item_key, item_value in self._list if item_key == key]267268 def keys(self) -> typing.KeysView:269 return self._dict.keys()270271 def values(self) -> typing.ValuesView:272 return self._dict.values()273274 def items(self) -> typing.ItemsView:275 return self._dict.items()276277 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:278 return list(self._list)279280 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:281 if key in self._dict:282 return self._dict[key]283 return default284285 def __getitem__(self, key: typing.Any) -> str:286 return self._dict[key]287288 def __contains__(self, key: typing.Any) -> bool:289 return key in self._dict290291 def __iter__(self) -> typing.Iterator[typing.Any]:292 return iter(self.keys())293294 def __len__(self) -> int:295 return len(self._dict)296297 def __eq__(self, other: typing.Any) -> bool:298 if not isinstance(other, self.__class__):299 return False300 return sorted(self._list) == sorted(other._list)301302 def __str__(self) -> str:303 return urlencode(self._list)304305 def __repr__(self) -> str:306 class_name = self.__class__.__name__307 query_string = str(self)308 return f"{class_name}({query_string!r})"309310311class Headers(typing.MutableMapping[str, str]):312 """313 HTTP headers, as a case-insensitive multi-dict.314 """315316 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:317 if headers is None:318 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]319 elif isinstance(headers, Headers):320 self._list = list(headers.raw)321 elif isinstance(headers, dict):322 self._list = [323 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))324 for k, v in headers.items()325 ]326 else:327 self._list = [328 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))329 for k, v in headers330 ]331 self._encoding = encoding332333 @property334 def encoding(self) -> str:335 """336 Header encoding is mandated as ascii, but we allow fallbacks to utf-8337 or iso-8859-1.338 """339 if self._encoding is None:340 for encoding in ["ascii", "utf-8"]:341 for key, value in self.raw:342 try:343 key.decode(encoding)344 value.decode(encoding)345 except UnicodeDecodeError:346 break347 else:348 # The else block runs if 'break' did not occur, meaning349 # all values fitted the encoding.350 self._encoding = encoding351 break352 else:353 # The ISO-8859-1 encoding covers all 256 code points in a byte,354 # so will never raise decode errors.355 self._encoding = "iso-8859-1"356 return self._encoding357358 @encoding.setter359 def encoding(self, value: str) -> None:360 self._encoding = value361362 @property363 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:364 """365 Returns a list of the raw header items, as byte pairs.366 May be mutated in-place.367 """368 return self._list369370 def keys(self) -> typing.List[str]: # type: ignore371 return [key.decode(self.encoding) for key, value in self._list]372373 def values(self) -> typing.List[str]: # type: ignore374 return [value.decode(self.encoding) for key, value in self._list]375376 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore377 return [378 (key.decode(self.encoding), value.decode(self.encoding))379 for key, value in self._list380 ]381382 def get(self, key: str, default: typing.Any = None) -> typing.Any:383 try:384 return self[key]385 except KeyError:386 return default387388 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:389 """390 Return multiple header values.391 """392 get_header_key = key.lower().encode(self.encoding)393394 values = [395 item_value.decode(self.encoding)396 for item_key, item_value in self._list397 if item_key == get_header_key398 ]399400 if not split_commas:401 return values402403 split_values = []404 for value in values:405 split_values.extend([item.strip() for item in value.split(",")])406 return split_values407408 def __getitem__(self, key: str) -> str:409 """410 Return a single header value.411412 If there are multiple headers with the same key, then we concatenate413 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2414 """415 normalized_key = key.lower().encode(self.encoding)416417 items = []418 for header_key, header_value in self._list:419 if header_key == normalized_key:420 items.append(header_value.decode(self.encoding))421422 if items:423 return ", ".join(items)424425 raise KeyError(key)426427 def __setitem__(self, key: str, value: str) -> None:428 """429 Set the header `key` to `value`, removing any duplicate entries.430 Retains insertion order.431 """432 set_key = key.lower().encode(self.encoding)433 set_value = value.encode(self.encoding)434435 found_indexes = []436 for idx, (item_key, item_value) in enumerate(self._list):437 if item_key == set_key:438 found_indexes.append(idx)439440 for idx in reversed(found_indexes[1:]):441 del self._list[idx]442443 if found_indexes:444 idx = found_indexes[0]445 self._list[idx] = (set_key, set_value)446 else:447 self._list.append((set_key, set_value))448449 def __delitem__(self, key: str) -> None:450 """451 Remove the header `key`.452 """453 del_key = key.lower().encode(self.encoding)454455 pop_indexes = []456 for idx, (item_key, item_value) in enumerate(self._list):457 if item_key == del_key:458 pop_indexes.append(idx)459460 for idx in reversed(pop_indexes):461 del self._list[idx]462463 def __contains__(self, key: typing.Any) -> bool:464 get_header_key = key.lower().encode(self.encoding)465 for header_key, header_value in self._list:466 if header_key == get_header_key:467 return True468 return False469470 def __iter__(self) -> typing.Iterator[typing.Any]:471 return iter(self.keys())472473 def __len__(self) -> int:474 return len(self._list)475476 def __eq__(self, other: typing.Any) -> bool:477 if not isinstance(other, Headers):478 return False479 return sorted(self._list) == sorted(other._list)480481 def __repr__(self) -> str:482 class_name = self.__class__.__name__483484 encoding_str = ""485 if self.encoding != "ascii":486 encoding_str = f", encoding={self.encoding!r}"487488 as_dict = dict(self.items())489 if len(as_dict) == len(self):490 return f"{class_name}({as_dict!r}{encoding_str})"491 as_list = self.items()492 return f"{class_name}({as_list!r}{encoding_str})"493494495class BaseRequest:496 def __init__(497 self,498 method: str,499 url: typing.Union[str, URL],500 *,501 params: QueryParamTypes = None,502 headers: HeaderTypes = None,503 cookies: CookieTypes = None,504 ):505 self.method = method.upper()506 self.url = URL(url, params=params)507 self.headers = Headers(headers)508 if cookies:509 self._cookies = Cookies(cookies)510 self._cookies.set_cookie_header(self)511Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 512–526why, one step back512 def encode_data(513 self, data: dict = None, files: RequestFiles = None, json: typing.Any = None514 ) -> typing.Tuple[bytes, str]:515 if json is not None:516 content = jsonlib.dumps(json).encode("utf-8")517 content_type = "application/json"518 elif files is not None:519 content, content_type = multipart_encode(data or {}, files)520 elif data is not None:521 content = urlencode(data, doseq=True).encode("utf-8")522 content_type = "application/x-www-form-urlencoded"523 else:524 content = b""525 content_type = ""526 return content, content_typehttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 527–533why, one step back527528 def prepare(self) -> None:529 content = getattr(self, "content", None) # type: bytes530 is_streaming = getattr(self, "is_streaming", False)531532 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]533Include host header directly (#109)Tom Christiebefore adoption5539b69
line 534why, one step back534 has_host = "host" in self.headershttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 535–540why, one step back535 has_user_agent = "user-agent" in self.headers536 has_accept = "accept" in self.headers537 has_content_length = (538 "content-length" in self.headers or "transfer-encoding" in self.headers539 )540 has_accept_encoding = "accept-encoding" in self.headersMinor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
line 541why, one step back541 has_connection = "connection" in self.headershttp3 (#86)Tom Christiebefore adoptionc9747aa
line 542why, one step back542Include host header directly (#109)Tom Christiebefore adoption5539b69
lines 543–544why, one step back543 if not has_host:544 auto_headers.append((b"host", self.url.authority.encode("ascii")))http3 (#86)Tom Christiebefore adoptionc9747aa
line 545why, one step back545 if not has_user_agent:Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
line 546why, one step back546 auto_headers.append((b"user-agent", USER_AGENT.encode("ascii")))http3 (#86)Tom Christiebefore adoptionc9747aa
lines 547–556why, one step back547 if not has_accept:548 auto_headers.append((b"accept", b"*/*"))549 if not has_content_length:550 if is_streaming:551 auto_headers.append((b"transfer-encoding", b"chunked"))552 elif content:553 content_length = str(len(content)).encode()554 auto_headers.append((b"content-length", content_length))555 if not has_accept_encoding:556 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
lines 557–558why, one step back557 if not has_connection:558 auto_headers.append((b"connection", b"keep-alive"))http3 (#86)Tom Christiebefore adoptionc9747aa
lines 559–583why, one step back559560 for item in reversed(auto_headers):561 self.headers.raw.insert(0, item)562563 @property564 def cookies(self) -> "Cookies":565 if not hasattr(self, "_cookies"):566 self._cookies = Cookies()567 return self._cookies568569 def __repr__(self) -> str:570 class_name = self.__class__.__name__571 url = str(self.url)572 return f"<{class_name}({self.method!r}, {url!r})>"573574575class AsyncRequest(BaseRequest):576 def __init__(577 self,578 method: str,579 url: typing.Union[str, URL],580 *,581 params: QueryParamTypes = None,582 headers: HeaderTypes = None,583 cookies: CookieTypes = None,Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 584–585why, one step back584 data: AsyncRequestData = None,585 files: RequestFiles = None,http3 (#86)Tom Christiebefore adoptionc9747aa
lines 586–591why, one step back586 json: typing.Any = None,587 ):588 super().__init__(589 method=method, url=url, params=params, headers=headers, cookies=cookies590 )591Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 592–593why, one step back592 if data is None or isinstance(data, dict):593 content, content_type = self.encode_data(data, files, json)http3 (#86)Tom Christiebefore adoptionc9747aa
line 594why, one step back594 self.is_streaming = FalseMultipart support (#90)Tom Christiebefore adoption6a44b05
lines 595–597why, one step back595 self.content = content596 if content_type:597 self.headers["Content-Type"] = content_typeInclude host header directly (#109)Tom Christiebefore adoption5539b69
lines 598–599why, one step back598 elif isinstance(data, (str, bytes)):599 data = data.encode("utf-8") if isinstance(data, str) else datahttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 600–633why, one step back600 self.is_streaming = False601 self.content = data602 else:603 assert hasattr(data, "__aiter__")604 self.is_streaming = True605 self.content_aiter = data606607 self.prepare()608609 async def read(self) -> bytes:610 """611 Read and return the response content.612 """613 if not hasattr(self, "content"):614 self.content = b"".join([part async for part in self.stream()])615 return self.content616617 async def stream(self) -> typing.AsyncIterator[bytes]:618 if self.is_streaming:619 async for part in self.content_aiter:620 yield part621 elif self.content:622 yield self.content623624625class Request(BaseRequest):626 def __init__(627 self,628 method: str,629 url: typing.Union[str, URL],630 *,631 params: QueryParamTypes = None,632 headers: HeaderTypes = None,633 cookies: CookieTypes = None,Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 634–635why, one step back634 data: RequestData = None,635 files: RequestFiles = None,http3 (#86)Tom Christiebefore adoptionc9747aa
lines 636–641why, one step back636 json: typing.Any = None,637 ):638 super().__init__(639 method=method, url=url, params=params, headers=headers, cookies=cookies640 )641Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 642–643why, one step back642 if data is None or isinstance(data, dict):643 content, content_type = self.encode_data(data, files, json)http3 (#86)Tom Christiebefore adoptionc9747aa
line 644why, one step back644 self.is_streaming = FalseMultipart support (#90)Tom Christiebefore adoption6a44b05
lines 645–647why, one step back645 self.content = content646 if content_type:647 self.headers["Content-Type"] = content_typeInclude host header directly (#109)Tom Christiebefore adoption5539b69
lines 648–649why, one step back648 elif isinstance(data, (str, bytes)):649 data = data.encode("utf-8") if isinstance(data, str) else datahttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 650–681why, one step back650 self.is_streaming = False651 self.content = data652 else:653 assert hasattr(data, "__iter__")654 self.is_streaming = True655 self.content_iter = data656657 self.prepare()658659 def read(self) -> bytes:660 if not hasattr(self, "content"):661 self.content = b"".join([part for part in self.stream()])662 return self.content663664 def stream(self) -> typing.Iterator[bytes]:665 if self.is_streaming:666 for part in self.content_iter:667 yield part668 elif self.content:669 yield self.content670671672class BaseResponse:673 def __init__(674 self,675 status_code: int,676 *,677 protocol: str = None,678 headers: HeaderTypes = None,679 request: BaseRequest = None,680 on_close: typing.Callable = None,681 ):Int status codes (#92)Tom Christiebefore adoption56a7943
line 682why, one step back682 self.status_code = status_codehttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 683–690why, one step back683 self.protocol = protocol684 self.headers = Headers(headers)685686 self.request = request687 self.on_close = on_close688 self.next = None # typing.Optional[typing.Callable]689690 @propertyInt status codes (#92)Tom Christiebefore adoption56a7943
lines 691–694why, one step back691 def reason_phrase(self) -> str:692 return StatusCode.get_reason_phrase(self.status_code)693694 @propertyhttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 695–815why, one step back695 def url(self) -> typing.Optional[URL]:696 """697 Returns the URL for which the request was made.698699 Requires that `request` was provided when instantiating the response.700 """701 return None if self.request is None else self.request.url702703 @property704 def content(self) -> bytes:705 if not hasattr(self, "_content"):706 if hasattr(self, "_raw_content"):707 raw_content = getattr(self, "_raw_content") # type: bytes708 content = self.decoder.decode(raw_content)709 content += self.decoder.flush()710 self._content = content711 else:712 raise ResponseNotRead()713 return self._content714715 @property716 def text(self) -> str:717 if not hasattr(self, "_text"):718 content = self.content719 if not content:720 self._text = ""721 else:722 encoding = self.encoding723 self._text = content.decode(encoding, errors="replace")724 return self._text725726 @property727 def encoding(self) -> str:728 if not hasattr(self, "_encoding"):729 encoding = self.charset_encoding730 if encoding is None or not is_known_encoding(encoding):731 encoding = self.apparent_encoding732 if encoding is None or not is_known_encoding(encoding):733 encoding = "utf-8"734 self._encoding = encoding735 return self._encoding736737 @encoding.setter738 def encoding(self, value: str) -> None:739 self._encoding = value740741 @property742 def charset_encoding(self) -> typing.Optional[str]:743 """744 Return the encoding, as specified by the Content-Type header.745 """746 content_type = self.headers.get("Content-Type")747 if content_type is None:748 return None749750 parsed = cgi.parse_header(content_type)751 media_type, params = parsed[0], parsed[-1]752 if "charset" in params:753 return params["charset"].strip("'\"")754755 # RFC 2616 specifies that 'iso-8859-1' should be used as the default756 # for 'text/*' media types, if no charset is provided.757 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1758 if media_type.startswith("text/"):759 return "iso-8859-1"760761 return None762763 @property764 def apparent_encoding(self) -> typing.Optional[str]:765 """766 Return the encoding, as it appears to autodetection.767 """768 return chardet.detect(self.content)["encoding"]769770 @property771 def decoder(self) -> Decoder:772 """773 Returns a decoder instance which can be used to decode the raw byte774 content, depending on the Content-Encoding used in the response.775 """776 if not hasattr(self, "_decoder"):777 decoders = [] # type: typing.List[Decoder]778 values = self.headers.getlist("content-encoding", split_commas=True)779 for value in values:780 value = value.strip().lower()781 decoder_cls = SUPPORTED_DECODERS[value]782 decoders.append(decoder_cls())783784 if len(decoders) == 1:785 self._decoder = decoders[0]786 elif len(decoders) > 1:787 self._decoder = MultiDecoder(decoders)788 else:789 self._decoder = IdentityDecoder()790791 return self._decoder792793 @property794 def is_redirect(self) -> bool:795 return StatusCode.is_redirect(self.status_code) and "location" in self.headers796797 def raise_for_status(self) -> None:798 """799 Raise the `HttpError` if one occurred.800 """801 message = (802 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"803 "For more information check: https://httpstatuses.com/{0.status_code}"804 )805806 if StatusCode.is_client_error(self.status_code):807 message = message.format(self, error_type="Client Error")808 elif StatusCode.is_server_error(self.status_code):809 message = message.format(self, error_type="Server Error")810 else:811 message = ""812813 if message:814 raise HttpError(message)815Encoding detection in Response.json (#116)Yeray Diaz Diazbefore adoption5442006
lines 816–824why, one step back816 def json(self, **kwargs: typing.Any) -> typing.Union[dict, list]:817 if self.charset_encoding is None and self.content and len(self.content) > 3:818 encoding = guess_json_utf(self.content)819 if encoding is not None:820 try:821 return jsonlib.loads(self.content.decode(encoding), **kwargs)822 except UnicodeDecodeError:823 pass824 return jsonlib.loads(self.text, **kwargs)http3 (#86)Tom Christiebefore adoptionc9747aa
lines 825–834why, one step back825826 @property827 def cookies(self) -> "Cookies":828 if not hasattr(self, "_cookies"):829 assert self.request is not None830 self._cookies = Cookies()831 self._cookies.extract_cookies(self)832 return self._cookies833834 def __repr__(self) -> str:Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4
line 835why, one step back835 return f"<Response [{self.status_code} {self.reason_phrase}]>"http3 (#86)Tom Christiebefore adoptionc9747aa
lines 836–844why, one step back836837838class AsyncResponse(BaseResponse):839 def __init__(840 self,841 status_code: int,842 *,843 protocol: str = None,844 headers: HeaderTypes = None,Multipart support (#90)Tom Christiebefore adoption6a44b05
line 845why, one step back845 content: AsyncResponseContent = None,http3 (#86)Tom Christiebefore adoptionc9747aa
lines 846–859why, one step back846 on_close: typing.Callable = None,847 request: AsyncRequest = None,848 history: typing.List["BaseResponse"] = None,849 ):850 super().__init__(851 status_code=status_code,852 protocol=protocol,853 headers=headers,854 request=request,855 on_close=on_close,856 )857858 self.history = [] if history is None else list(history)859Multipart support (#90)Tom Christiebefore adoption6a44b05
line 860why, one step back860 if content is None or isinstance(content, bytes):http3 (#86)Tom Christiebefore adoptionc9747aa
lines 861–862why, one step back861 self.is_closed = True862 self.is_stream_consumed = TrueMultipart support (#90)Tom Christiebefore adoption6a44b05
line 863why, one step back863 self._raw_content = content or b""http3 (#86)Tom Christiebefore adoptionc9747aa
lines 864–923why, one step back864 else:865 self.is_closed = False866 self.is_stream_consumed = False867 self._raw_stream = content868869 async def read(self) -> bytes:870 """871 Read and return the response content.872 """873 if not hasattr(self, "_content"):874 self._content = b"".join([part async for part in self.stream()])875 return self._content876877 async def stream(self) -> typing.AsyncIterator[bytes]:878 """879 A byte-iterator over the decoded response content.880 This allows us to handle gzip, deflate, and brotli encoded responses.881 """882 if hasattr(self, "_content"):883 yield self._content884 else:885 async for chunk in self.raw():886 yield self.decoder.decode(chunk)887 yield self.decoder.flush()888889 async def raw(self) -> typing.AsyncIterator[bytes]:890 """891 A byte-iterator over the raw response content.892 """893 if hasattr(self, "_raw_content"):894 yield self._raw_content895 else:896 if self.is_stream_consumed:897 raise StreamConsumed()898 if self.is_closed:899 raise ResponseClosed()900901 self.is_stream_consumed = True902 async for part in self._raw_stream:903 yield part904 await self.close()905906 async def close(self) -> None:907 """908 Close the response and release the connection.909 Automatically called if the response body is read to completion.910 """911 if not self.is_closed:912 self.is_closed = True913 if self.on_close is not None:914 await self.on_close()915916917class Response(BaseResponse):918 def __init__(919 self,920 status_code: int,921 *,922 protocol: str = None,923 headers: HeaderTypes = None,Multipart support (#90)Tom Christiebefore adoption6a44b05
line 924why, one step back924 content: ResponseContent = None,http3 (#86)Tom Christiebefore adoptionc9747aa
lines 925–938why, one step back925 on_close: typing.Callable = None,926 request: Request = None,927 history: typing.List["BaseResponse"] = None,928 ):929 super().__init__(930 status_code=status_code,931 protocol=protocol,932 headers=headers,933 request=request,934 on_close=on_close,935 )936937 self.history = [] if history is None else list(history)938Multipart support (#90)Tom Christiebefore adoption6a44b05
line 939why, one step back939 if content is None or isinstance(content, bytes):http3 (#86)Tom Christiebefore adoptionc9747aa
lines 940–941why, one step back940 self.is_closed = True941 self.is_stream_consumed = TrueMultipart support (#90)Tom Christiebefore adoption6a44b05
line 942why, one step back942 self._raw_content = content or b""http3 (#86)Tom Christiebefore adoptionc9747aa
lines 943–1168why, one step back943 else:944 self.is_closed = False945 self.is_stream_consumed = False946 self._raw_stream = content947948 def read(self) -> bytes:949 """950 Read and return the response content.951 """952 if not hasattr(self, "_content"):953 self._content = b"".join([part for part in self.stream()])954 return self._content955956 def stream(self) -> typing.Iterator[bytes]:957 """958 A byte-iterator over the decoded response content.959 This allows us to handle gzip, deflate, and brotli encoded responses.960 """961 if hasattr(self, "_content"):962 yield self._content963 else:964 for chunk in self.raw():965 yield self.decoder.decode(chunk)966 yield self.decoder.flush()967968 def raw(self) -> typing.Iterator[bytes]:969 """970 A byte-iterator over the raw response content.971 """972 if hasattr(self, "_raw_content"):973 yield self._raw_content974 else:975 if self.is_stream_consumed:976 raise StreamConsumed()977 if self.is_closed:978 raise ResponseClosed()979980 self.is_stream_consumed = True981 for part in self._raw_stream:982 yield part983 self.close()984985 def close(self) -> None:986 """987 Close the response and release the connection.988 Automatically called if the response body is read to completion.989 """990 if not self.is_closed:991 self.is_closed = True992 if self.on_close is not None:993 self.on_close()994995996class Cookies(MutableMapping):997 """998 HTTP Cookies, as a mutable mapping.999 """10001001 def __init__(self, cookies: CookieTypes = None) -> None:1002 if cookies is None or isinstance(cookies, dict):1003 self.jar = CookieJar()1004 if isinstance(cookies, dict):1005 for key, value in cookies.items():1006 self.set(key, value)1007 elif isinstance(cookies, Cookies):1008 self.jar = CookieJar()1009 for cookie in cookies.jar:1010 self.jar.set_cookie(cookie)1011 else:1012 self.jar = cookies10131014 def extract_cookies(self, response: BaseResponse) -> None:1015 """1016 Loads any cookies based on the response `Set-Cookie` headers.1017 """1018 assert response.request is not None1019 urlib_response = self._CookieCompatResponse(response)1020 urllib_request = self._CookieCompatRequest(response.request)10211022 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore10231024 def set_cookie_header(self, request: BaseRequest) -> None:1025 """1026 Sets an appropriate 'Cookie:' HTTP header on the `Request`.1027 """1028 urllib_request = self._CookieCompatRequest(request)1029 self.jar.add_cookie_header(urllib_request)10301031 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:1032 """1033 Set a cookie value by name. May optionally include domain and path.1034 """1035 kwargs = dict(1036 version=0,1037 name=name,1038 value=value,1039 port=None,1040 port_specified=False,1041 domain=domain,1042 domain_specified=bool(domain),1043 domain_initial_dot=domain.startswith("."),1044 path=path,1045 path_specified=bool(path),1046 secure=False,1047 expires=None,1048 discard=True,1049 comment=None,1050 comment_url=None,1051 rest={"HttpOnly": None},1052 rfc2109=False,1053 )1054 cookie = Cookie(**kwargs) # type: ignore1055 self.jar.set_cookie(cookie)10561057 def get( # type: ignore1058 self, name: str, default: str = None, domain: str = None, path: str = None1059 ) -> typing.Optional[str]:1060 """1061 Get a cookie by name. May optionally include domain and path1062 in order to specify exactly which cookie to retrieve.1063 """1064 value = None1065 for cookie in self.jar:1066 if cookie.name == name:1067 if domain is None or cookie.domain == domain: # type: ignore1068 if path is None or cookie.path == path:1069 if value is not None:1070 message = f"Multiple cookies exist with name={name}"1071 raise CookieConflict(message)1072 value = cookie.value10731074 if value is None:1075 return default1076 return value10771078 def delete(self, name: str, domain: str = None, path: str = None) -> None:1079 """1080 Delete a cookie by name. May optionally include domain and path1081 in order to specify exactly which cookie to delete.1082 """1083 if domain is not None and path is not None:1084 return self.jar.clear(domain, path, name)10851086 remove = []1087 for cookie in self.jar:1088 if cookie.name == name:1089 if domain is None or cookie.domain == domain: # type: ignore1090 if path is None or cookie.path == path:1091 remove.append(cookie)10921093 for cookie in remove:1094 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore10951096 def clear(self, domain: str = None, path: str = None) -> None:1097 """1098 Delete all cookies. Optionally include a domain and path in1099 order to only delete a subset of all the cookies.1100 """1101 args = []1102 if domain is not None:1103 args.append(domain)1104 if path is not None:1105 assert domain is not None1106 args.append(path)1107 self.jar.clear(*args)11081109 def update(self, cookies: CookieTypes = None) -> None: # type: ignore1110 cookies = Cookies(cookies)1111 for cookie in cookies.jar:1112 self.jar.set_cookie(cookie)11131114 def __setitem__(self, name: str, value: str) -> None:1115 return self.set(name, value)11161117 def __getitem__(self, name: str) -> str:1118 value = self.get(name)1119 if value is None:1120 raise KeyError(name)1121 return value11221123 def __delitem__(self, name: str) -> None:1124 return self.delete(name)11251126 def __len__(self) -> int:1127 return len(self.jar)11281129 def __iter__(self) -> typing.Iterator[str]:1130 return (cookie.name for cookie in self.jar)11311132 def __bool__(self) -> bool:1133 for cookie in self.jar:1134 return True1135 return False11361137 class _CookieCompatRequest(urllib.request.Request):1138 """1139 Wraps a `Request` instance up in a compatability interface suitable1140 for use with `CookieJar` operations.1141 """11421143 def __init__(self, request: BaseRequest) -> None:1144 super().__init__(1145 url=str(request.url),1146 headers=dict(request.headers),1147 method=request.method,1148 )1149 self.request = request11501151 def add_unredirected_header(self, key: str, value: str) -> None:1152 super().add_unredirected_header(key, value)1153 self.request.headers[key] = value11541155 class _CookieCompatResponse:1156 """1157 Wraps a `Request` instance up in a compatability interface suitable1158 for use with `CookieJar` operations.1159 """11601161 def __init__(self, response: BaseResponse):1162 self.response = response11631164 def info(self) -> email.message.Message:1165 info = email.message.Message()1166 for key, value in self.response.headers.items():1167 info[key] = value1168 return info