models.py
This file
Path
http3/models.py
1,154 lines · 36.2 KiB · Python
Last changed by
Include host header directly (#109)Tom Christiebefore adoption5539b69
History of this fileTake it
http3 (#86)Tom Christiebefore adoptionc9747aa
lines 1–27why, 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 rfc39861213from .decoders import (14 ACCEPT_ENCODING,15 SUPPORTED_DECODERS,16 Decoder,17 IdentityDecoder,18 MultiDecoder,19)20from .exceptions import (21 CookieConflict,22 HttpError,23 InvalidURL,24 ResponseClosed,25 ResponseNotRead,26 StreamConsumed,27)Multipart support (#90)Tom Christiebefore adoption6a44b05
line 28why, one step back28from .multipart import multipart_encodehttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 29–53why, one step back29from .status_codes import StatusCode30from .utils import is_known_encoding, normalize_header_key, normalize_header_value3132URLTypes = typing.Union["URL", str]3334QueryParamTypes = typing.Union[35 "QueryParams",36 typing.Mapping[str, str],37 typing.List[typing.Tuple[typing.Any, typing.Any]],38 str,39]4041HeaderTypes = typing.Union[42 "Headers",43 typing.Dict[typing.AnyStr, typing.AnyStr],44 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],45]4647CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]4849AuthTypes = typing.Union[50 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],51 typing.Callable[["AsyncRequest"], "AsyncRequest"],52]53Include host header directly (#109)Tom Christiebefore adoption5539b69
line 54why, one step back54AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]http3 (#86)Tom Christiebefore adoptionc9747aa
line 55why, one step back55Include host header directly (#109)Tom Christiebefore adoption5539b69
line 56why, one step back56RequestData = typing.Union[dict, str, bytes, typing.Iterator[bytes]]http3 (#86)Tom Christiebefore adoptionc9747aa
line 57why, one step back57Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 58–68why, one step back58RequestFiles = typing.Dict[59 str,60 typing.Union[61 typing.IO[typing.AnyStr], # file62 typing.Tuple[str, typing.IO[typing.AnyStr]], # (filename, file)63 typing.Tuple[64 str, typing.IO[typing.AnyStr], str65 ], # (filename, file, content_type)66 ],67]68http3 (#86)Tom Christiebefore adoptionc9747aa
lines 69–185why, one step back69AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]7071ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]727374class URL:75 def __init__(76 self,77 url: URLTypes,78 allow_relative: bool = False,79 params: QueryParamTypes = None,80 ) -> None:81 if isinstance(url, rfc3986.uri.URIReference):82 self.components = url83 elif isinstance(url, str):84 self.components = rfc3986.api.uri_reference(url)85 else:86 self.components = url.components8788 # Handle IDNA domain names.89 if self.components.authority:90 idna_authority = self.components.authority.encode("idna").decode("ascii")91 if idna_authority != self.components.authority:92 self.components = self.components.copy_with(authority=idna_authority)9394 # Normalize scheme and domain name.95 self.components = self.components.normalize()9697 # Add any query parameters.98 if params:99 query_string = str(QueryParams(params))100 self.components = self.components.copy_with(query=query_string)101102 # Enforce absolute URLs by default.103 if not allow_relative:104 if not self.scheme:105 raise InvalidURL("No scheme included in URL.")106 if self.scheme not in ("http", "https"):107 raise InvalidURL('URL scheme must be "http" or "https".')108 if not self.host:109 raise InvalidURL("No host included in URL.")110111 @property112 def scheme(self) -> str:113 return self.components.scheme or ""114115 @property116 def authority(self) -> str:117 return self.components.authority or ""118119 @property120 def username(self) -> str:121 userinfo = self.components.userinfo or ""122 return userinfo.partition(":")[0]123124 @property125 def password(self) -> str:126 userinfo = self.components.userinfo or ""127 return userinfo.partition(":")[2]128129 @property130 def host(self) -> str:131 return self.components.host or ""132133 @property134 def port(self) -> int:135 port = self.components.port136 if port is None:137 return {"https": 443, "http": 80}[self.scheme]138 return int(port)139140 @property141 def path(self) -> str:142 return self.components.path or "/"143144 @property145 def query(self) -> str:146 return self.components.query or ""147148 @property149 def full_path(self) -> str:150 path = self.path151 if self.query:152 path += "?" + self.query153 return path154155 @property156 def fragment(self) -> str:157 return self.components.fragment or ""158159 @property160 def is_ssl(self) -> bool:161 return self.components.scheme == "https"162163 @property164 def is_absolute_url(self) -> bool:165 """166 Return `True` for absolute URLs such as 'http://example.com/path',167 and `False` for relative URLs such as '/path'.168 """169 # We don't use rfc3986's `is_absolute` because it treats170 # URLs with a fragment portion as not absolute.171 # What we actually care about is if the URL provides172 # a scheme and hostname to which connections should be made.173 return self.components.scheme and self.components.host174175 @property176 def is_relative_url(self) -> bool:177 return not self.is_absolute_url178179 @property180 def origin(self) -> "Origin":181 return Origin(self)182183 def copy_with(self, **kwargs: typing.Any) -> "URL":184 return URL(self.components.copy_with(**kwargs))185Support Client(base_url=...)Tom Christiebefore adoption9d5aaff
line 186why, one step back186 def join(self, relative_url: URLTypes) -> "URL":http3 (#86)Tom Christiebefore adoptionc9747aa
line 187why, one step back187 """Support Client(base_url=...)Tom Christiebefore adoption9d5aaff
line 188why, one step back188 Return an absolute URL, using given this URL as the base.http3 (#86)Tom Christiebefore adoptionc9747aa
line 189why, one step back189 """Support Client(base_url=...)Tom Christiebefore adoption9d5aaff
lines 190–192why, one step back190 if self.is_relative_url:191 return URL(relative_url)192http3 (#86)Tom Christiebefore adoptionc9747aa
lines 193–194why, one step back193 # We drop any fragment portion, because RFC 3986 strictly194 # treats URLs with a fragment portion as not being absolute URLs.Support Client(base_url=...)Tom Christiebefore adoption9d5aaff
lines 195–197why, one step back195 base_components = self.components.copy_with(fragment=None)196 relative_url = URL(relative_url, allow_relative=True)197 return URL(relative_url.components.resolve_with(base_components))http3 (#86)Tom Christiebefore adoptionc9747aa
lines 198–507why, one step back198199 def __hash__(self) -> int:200 return hash(str(self))201202 def __eq__(self, other: typing.Any) -> bool:203 return isinstance(other, URL) and str(self) == str(other)204205 def __str__(self) -> str:206 return self.components.unsplit()207208 def __repr__(self) -> str:209 class_name = self.__class__.__name__210 url_str = str(self)211 return f"{class_name}({url_str!r})"212213214class Origin:215 """216 The URL scheme and authority information, as a comparable, hashable object.217 """218219 def __init__(self, url: URLTypes) -> None:220 if not isinstance(url, URL):221 url = URL(url)222 self.is_ssl = url.is_ssl223 self.host = url.host224 self.port = url.port225226 def __eq__(self, other: typing.Any) -> bool:227 return (228 isinstance(other, self.__class__)229 and self.is_ssl == other.is_ssl230 and self.host == other.host231 and self.port == other.port232 )233234 def __hash__(self) -> int:235 return hash((self.is_ssl, self.host, self.port))236237238class QueryParams(typing.Mapping[str, str]):239 """240 URL query parameters, as a multi-dict.241 """242243 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:244 assert len(args) < 2, "Too many arguments."245 assert not (args and kwargs), "Cannot mix named and unnamed arguments."246247 value = args[0] if args else kwargs248249 if isinstance(value, str):250 items = parse_qsl(value)251 elif isinstance(value, QueryParams):252 items = value.multi_items()253 elif isinstance(value, list):254 items = value255 else:256 items = value.items() # type: ignore257258 self._list = [(str(k), str(v)) for k, v in items]259 self._dict = {str(k): str(v) for k, v in items}260261 def getlist(self, key: typing.Any) -> typing.List[str]:262 return [item_value for item_key, item_value in self._list if item_key == key]263264 def keys(self) -> typing.KeysView:265 return self._dict.keys()266267 def values(self) -> typing.ValuesView:268 return self._dict.values()269270 def items(self) -> typing.ItemsView:271 return self._dict.items()272273 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:274 return list(self._list)275276 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:277 if key in self._dict:278 return self._dict[key]279 return default280281 def __getitem__(self, key: typing.Any) -> str:282 return self._dict[key]283284 def __contains__(self, key: typing.Any) -> bool:285 return key in self._dict286287 def __iter__(self) -> typing.Iterator[typing.Any]:288 return iter(self.keys())289290 def __len__(self) -> int:291 return len(self._dict)292293 def __eq__(self, other: typing.Any) -> bool:294 if not isinstance(other, self.__class__):295 return False296 return sorted(self._list) == sorted(other._list)297298 def __str__(self) -> str:299 return urlencode(self._list)300301 def __repr__(self) -> str:302 class_name = self.__class__.__name__303 query_string = str(self)304 return f"{class_name}({query_string!r})"305306307class Headers(typing.MutableMapping[str, str]):308 """309 HTTP headers, as a case-insensitive multi-dict.310 """311312 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:313 if headers is None:314 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]315 elif isinstance(headers, Headers):316 self._list = list(headers.raw)317 elif isinstance(headers, dict):318 self._list = [319 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))320 for k, v in headers.items()321 ]322 else:323 self._list = [324 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))325 for k, v in headers326 ]327 self._encoding = encoding328329 @property330 def encoding(self) -> str:331 """332 Header encoding is mandated as ascii, but we allow fallbacks to utf-8333 or iso-8859-1.334 """335 if self._encoding is None:336 for encoding in ["ascii", "utf-8"]:337 for key, value in self.raw:338 try:339 key.decode(encoding)340 value.decode(encoding)341 except UnicodeDecodeError:342 break343 else:344 # The else block runs if 'break' did not occur, meaning345 # all values fitted the encoding.346 self._encoding = encoding347 break348 else:349 # The ISO-8859-1 encoding covers all 256 code points in a byte,350 # so will never raise decode errors.351 self._encoding = "iso-8859-1"352 return self._encoding353354 @encoding.setter355 def encoding(self, value: str) -> None:356 self._encoding = value357358 @property359 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:360 """361 Returns a list of the raw header items, as byte pairs.362 May be mutated in-place.363 """364 return self._list365366 def keys(self) -> typing.List[str]: # type: ignore367 return [key.decode(self.encoding) for key, value in self._list]368369 def values(self) -> typing.List[str]: # type: ignore370 return [value.decode(self.encoding) for key, value in self._list]371372 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore373 return [374 (key.decode(self.encoding), value.decode(self.encoding))375 for key, value in self._list376 ]377378 def get(self, key: str, default: typing.Any = None) -> typing.Any:379 try:380 return self[key]381 except KeyError:382 return default383384 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:385 """386 Return multiple header values.387 """388 get_header_key = key.lower().encode(self.encoding)389390 values = [391 item_value.decode(self.encoding)392 for item_key, item_value in self._list393 if item_key == get_header_key394 ]395396 if not split_commas:397 return values398399 split_values = []400 for value in values:401 split_values.extend([item.strip() for item in value.split(",")])402 return split_values403404 def __getitem__(self, key: str) -> str:405 """406 Return a single header value.407408 If there are multiple headers with the same key, then we concatenate409 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2410 """411 normalized_key = key.lower().encode(self.encoding)412413 items = []414 for header_key, header_value in self._list:415 if header_key == normalized_key:416 items.append(header_value.decode(self.encoding))417418 if items:419 return ", ".join(items)420421 raise KeyError(key)422423 def __setitem__(self, key: str, value: str) -> None:424 """425 Set the header `key` to `value`, removing any duplicate entries.426 Retains insertion order.427 """428 set_key = key.lower().encode(self.encoding)429 set_value = value.encode(self.encoding)430431 found_indexes = []432 for idx, (item_key, item_value) in enumerate(self._list):433 if item_key == set_key:434 found_indexes.append(idx)435436 for idx in reversed(found_indexes[1:]):437 del self._list[idx]438439 if found_indexes:440 idx = found_indexes[0]441 self._list[idx] = (set_key, set_value)442 else:443 self._list.append((set_key, set_value))444445 def __delitem__(self, key: str) -> None:446 """447 Remove the header `key`.448 """449 del_key = key.lower().encode(self.encoding)450451 pop_indexes = []452 for idx, (item_key, item_value) in enumerate(self._list):453 if item_key == del_key:454 pop_indexes.append(idx)455456 for idx in reversed(pop_indexes):457 del self._list[idx]458459 def __contains__(self, key: typing.Any) -> bool:460 get_header_key = key.lower().encode(self.encoding)461 for header_key, header_value in self._list:462 if header_key == get_header_key:463 return True464 return False465466 def __iter__(self) -> typing.Iterator[typing.Any]:467 return iter(self.keys())468469 def __len__(self) -> int:470 return len(self._list)471472 def __eq__(self, other: typing.Any) -> bool:473 if not isinstance(other, Headers):474 return False475 return sorted(self._list) == sorted(other._list)476477 def __repr__(self) -> str:478 class_name = self.__class__.__name__479480 encoding_str = ""481 if self.encoding != "ascii":482 encoding_str = f", encoding={self.encoding!r}"483484 as_dict = dict(self.items())485 if len(as_dict) == len(self):486 return f"{class_name}({as_dict!r}{encoding_str})"487 as_list = self.items()488 return f"{class_name}({as_list!r}{encoding_str})"489490491class BaseRequest:492 def __init__(493 self,494 method: str,495 url: typing.Union[str, URL],496 *,497 params: QueryParamTypes = None,498 headers: HeaderTypes = None,499 cookies: CookieTypes = None,500 ):501 self.method = method.upper()502 self.url = URL(url, params=params)503 self.headers = Headers(headers)504 if cookies:505 self._cookies = Cookies(cookies)506 self._cookies.set_cookie_header(self)507Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 508–522why, one step back508 def encode_data(509 self, data: dict = None, files: RequestFiles = None, json: typing.Any = None510 ) -> typing.Tuple[bytes, str]:511 if json is not None:512 content = jsonlib.dumps(json).encode("utf-8")513 content_type = "application/json"514 elif files is not None:515 content, content_type = multipart_encode(data or {}, files)516 elif data is not None:517 content = urlencode(data, doseq=True).encode("utf-8")518 content_type = "application/x-www-form-urlencoded"519 else:520 content = b""521 content_type = ""522 return content, content_typehttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 523–529why, one step back523524 def prepare(self) -> None:525 content = getattr(self, "content", None) # type: bytes526 is_streaming = getattr(self, "is_streaming", False)527528 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]529Include host header directly (#109)Tom Christiebefore adoption5539b69
line 530why, one step back530 has_host = "host" in self.headershttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 531–537why, one step back531 has_user_agent = "user-agent" in self.headers532 has_accept = "accept" in self.headers533 has_content_length = (534 "content-length" in self.headers or "transfer-encoding" in self.headers535 )536 has_accept_encoding = "accept-encoding" in self.headers537Include host header directly (#109)Tom Christiebefore adoption5539b69
lines 538–539why, one step back538 if not has_host:539 auto_headers.append((b"host", self.url.authority.encode("ascii")))http3 (#86)Tom Christiebefore adoptionc9747aa
lines 540–576why, one step back540 if not has_user_agent:541 auto_headers.append((b"user-agent", b"http3"))542 if not has_accept:543 auto_headers.append((b"accept", b"*/*"))544 if not has_content_length:545 if is_streaming:546 auto_headers.append((b"transfer-encoding", b"chunked"))547 elif content:548 content_length = str(len(content)).encode()549 auto_headers.append((b"content-length", content_length))550 if not has_accept_encoding:551 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))552553 for item in reversed(auto_headers):554 self.headers.raw.insert(0, item)555556 @property557 def cookies(self) -> "Cookies":558 if not hasattr(self, "_cookies"):559 self._cookies = Cookies()560 return self._cookies561562 def __repr__(self) -> str:563 class_name = self.__class__.__name__564 url = str(self.url)565 return f"<{class_name}({self.method!r}, {url!r})>"566567568class AsyncRequest(BaseRequest):569 def __init__(570 self,571 method: str,572 url: typing.Union[str, URL],573 *,574 params: QueryParamTypes = None,575 headers: HeaderTypes = None,576 cookies: CookieTypes = None,Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 577–578why, one step back577 data: AsyncRequestData = None,578 files: RequestFiles = None,http3 (#86)Tom Christiebefore adoptionc9747aa
lines 579–584why, one step back579 json: typing.Any = None,580 ):581 super().__init__(582 method=method, url=url, params=params, headers=headers, cookies=cookies583 )584Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 585–586why, one step back585 if data is None or isinstance(data, dict):586 content, content_type = self.encode_data(data, files, json)http3 (#86)Tom Christiebefore adoptionc9747aa
line 587why, one step back587 self.is_streaming = FalseMultipart support (#90)Tom Christiebefore adoption6a44b05
lines 588–590why, one step back588 self.content = content589 if content_type:590 self.headers["Content-Type"] = content_typeInclude host header directly (#109)Tom Christiebefore adoption5539b69
lines 591–592why, one step back591 elif isinstance(data, (str, bytes)):592 data = data.encode("utf-8") if isinstance(data, str) else datahttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 593–626why, one step back593 self.is_streaming = False594 self.content = data595 else:596 assert hasattr(data, "__aiter__")597 self.is_streaming = True598 self.content_aiter = data599600 self.prepare()601602 async def read(self) -> bytes:603 """604 Read and return the response content.605 """606 if not hasattr(self, "content"):607 self.content = b"".join([part async for part in self.stream()])608 return self.content609610 async def stream(self) -> typing.AsyncIterator[bytes]:611 if self.is_streaming:612 async for part in self.content_aiter:613 yield part614 elif self.content:615 yield self.content616617618class Request(BaseRequest):619 def __init__(620 self,621 method: str,622 url: typing.Union[str, URL],623 *,624 params: QueryParamTypes = None,625 headers: HeaderTypes = None,626 cookies: CookieTypes = None,Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 627–628why, one step back627 data: RequestData = None,628 files: RequestFiles = None,http3 (#86)Tom Christiebefore adoptionc9747aa
lines 629–634why, one step back629 json: typing.Any = None,630 ):631 super().__init__(632 method=method, url=url, params=params, headers=headers, cookies=cookies633 )634Multipart support (#90)Tom Christiebefore adoption6a44b05
lines 635–636why, one step back635 if data is None or isinstance(data, dict):636 content, content_type = self.encode_data(data, files, json)http3 (#86)Tom Christiebefore adoptionc9747aa
line 637why, one step back637 self.is_streaming = FalseMultipart support (#90)Tom Christiebefore adoption6a44b05
lines 638–640why, one step back638 self.content = content639 if content_type:640 self.headers["Content-Type"] = content_typeInclude host header directly (#109)Tom Christiebefore adoption5539b69
lines 641–642why, one step back641 elif isinstance(data, (str, bytes)):642 data = data.encode("utf-8") if isinstance(data, str) else datahttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 643–674why, one step back643 self.is_streaming = False644 self.content = data645 else:646 assert hasattr(data, "__iter__")647 self.is_streaming = True648 self.content_iter = data649650 self.prepare()651652 def read(self) -> bytes:653 if not hasattr(self, "content"):654 self.content = b"".join([part for part in self.stream()])655 return self.content656657 def stream(self) -> typing.Iterator[bytes]:658 if self.is_streaming:659 for part in self.content_iter:660 yield part661 elif self.content:662 yield self.content663664665class BaseResponse:666 def __init__(667 self,668 status_code: int,669 *,670 protocol: str = None,671 headers: HeaderTypes = None,672 request: BaseRequest = None,673 on_close: typing.Callable = None,674 ):Int status codes (#92)Tom Christiebefore adoption56a7943
line 675why, one step back675 self.status_code = status_codehttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 676–683why, one step back676 self.protocol = protocol677 self.headers = Headers(headers)678679 self.request = request680 self.on_close = on_close681 self.next = None # typing.Optional[typing.Callable]682683 @propertyInt status codes (#92)Tom Christiebefore adoption56a7943
lines 684–687why, one step back684 def reason_phrase(self) -> str:685 return StatusCode.get_reason_phrase(self.status_code)686687 @propertyhttp3 (#86)Tom Christiebefore adoptionc9747aa
lines 688–820why, one step back688 def url(self) -> typing.Optional[URL]:689 """690 Returns the URL for which the request was made.691692 Requires that `request` was provided when instantiating the response.693 """694 return None if self.request is None else self.request.url695696 @property697 def content(self) -> bytes:698 if not hasattr(self, "_content"):699 if hasattr(self, "_raw_content"):700 raw_content = getattr(self, "_raw_content") # type: bytes701 content = self.decoder.decode(raw_content)702 content += self.decoder.flush()703 self._content = content704 else:705 raise ResponseNotRead()706 return self._content707708 @property709 def text(self) -> str:710 if not hasattr(self, "_text"):711 content = self.content712 if not content:713 self._text = ""714 else:715 encoding = self.encoding716 self._text = content.decode(encoding, errors="replace")717 return self._text718719 @property720 def encoding(self) -> str:721 if not hasattr(self, "_encoding"):722 encoding = self.charset_encoding723 if encoding is None or not is_known_encoding(encoding):724 encoding = self.apparent_encoding725 if encoding is None or not is_known_encoding(encoding):726 encoding = "utf-8"727 self._encoding = encoding728 return self._encoding729730 @encoding.setter731 def encoding(self, value: str) -> None:732 self._encoding = value733734 @property735 def charset_encoding(self) -> typing.Optional[str]:736 """737 Return the encoding, as specified by the Content-Type header.738 """739 content_type = self.headers.get("Content-Type")740 if content_type is None:741 return None742743 parsed = cgi.parse_header(content_type)744 media_type, params = parsed[0], parsed[-1]745 if "charset" in params:746 return params["charset"].strip("'\"")747748 # RFC 2616 specifies that 'iso-8859-1' should be used as the default749 # for 'text/*' media types, if no charset is provided.750 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1751 if media_type.startswith("text/"):752 return "iso-8859-1"753754 return None755756 @property757 def apparent_encoding(self) -> typing.Optional[str]:758 """759 Return the encoding, as it appears to autodetection.760 """761 return chardet.detect(self.content)["encoding"]762763 @property764 def decoder(self) -> Decoder:765 """766 Returns a decoder instance which can be used to decode the raw byte767 content, depending on the Content-Encoding used in the response.768 """769 if not hasattr(self, "_decoder"):770 decoders = [] # type: typing.List[Decoder]771 values = self.headers.getlist("content-encoding", split_commas=True)772 for value in values:773 value = value.strip().lower()774 decoder_cls = SUPPORTED_DECODERS[value]775 decoders.append(decoder_cls())776777 if len(decoders) == 1:778 self._decoder = decoders[0]779 elif len(decoders) > 1:780 self._decoder = MultiDecoder(decoders)781 else:782 self._decoder = IdentityDecoder()783784 return self._decoder785786 @property787 def is_redirect(self) -> bool:788 return StatusCode.is_redirect(self.status_code) and "location" in self.headers789790 def raise_for_status(self) -> None:791 """792 Raise the `HttpError` if one occurred.793 """794 message = (795 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"796 "For more information check: https://httpstatuses.com/{0.status_code}"797 )798799 if StatusCode.is_client_error(self.status_code):800 message = message.format(self, error_type="Client Error")801 elif StatusCode.is_server_error(self.status_code):802 message = message.format(self, error_type="Server Error")803 else:804 message = ""805806 if message:807 raise HttpError(message)808809 def json(self) -> typing.Any:810 return jsonlib.loads(self.content.decode("utf-8"))811812 @property813 def cookies(self) -> "Cookies":814 if not hasattr(self, "_cookies"):815 assert self.request is not None816 self._cookies = Cookies()817 self._cookies.extract_cookies(self)818 return self._cookies819820 def __repr__(self) -> str:Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4
line 821why, one step back821 return f"<Response [{self.status_code} {self.reason_phrase}]>"http3 (#86)Tom Christiebefore adoptionc9747aa
lines 822–830why, one step back822823824class AsyncResponse(BaseResponse):825 def __init__(826 self,827 status_code: int,828 *,829 protocol: str = None,830 headers: HeaderTypes = None,Multipart support (#90)Tom Christiebefore adoption6a44b05
line 831why, one step back831 content: AsyncResponseContent = None,http3 (#86)Tom Christiebefore adoptionc9747aa
lines 832–845why, one step back832 on_close: typing.Callable = None,833 request: AsyncRequest = None,834 history: typing.List["BaseResponse"] = None,835 ):836 super().__init__(837 status_code=status_code,838 protocol=protocol,839 headers=headers,840 request=request,841 on_close=on_close,842 )843844 self.history = [] if history is None else list(history)845Multipart support (#90)Tom Christiebefore adoption6a44b05
line 846why, one step back846 if content is None or isinstance(content, bytes):http3 (#86)Tom Christiebefore adoptionc9747aa
lines 847–848why, one step back847 self.is_closed = True848 self.is_stream_consumed = TrueMultipart support (#90)Tom Christiebefore adoption6a44b05
line 849why, one step back849 self._raw_content = content or b""http3 (#86)Tom Christiebefore adoptionc9747aa
lines 850–909why, one step back850 else:851 self.is_closed = False852 self.is_stream_consumed = False853 self._raw_stream = content854855 async def read(self) -> bytes:856 """857 Read and return the response content.858 """859 if not hasattr(self, "_content"):860 self._content = b"".join([part async for part in self.stream()])861 return self._content862863 async def stream(self) -> typing.AsyncIterator[bytes]:864 """865 A byte-iterator over the decoded response content.866 This allows us to handle gzip, deflate, and brotli encoded responses.867 """868 if hasattr(self, "_content"):869 yield self._content870 else:871 async for chunk in self.raw():872 yield self.decoder.decode(chunk)873 yield self.decoder.flush()874875 async def raw(self) -> typing.AsyncIterator[bytes]:876 """877 A byte-iterator over the raw response content.878 """879 if hasattr(self, "_raw_content"):880 yield self._raw_content881 else:882 if self.is_stream_consumed:883 raise StreamConsumed()884 if self.is_closed:885 raise ResponseClosed()886887 self.is_stream_consumed = True888 async for part in self._raw_stream:889 yield part890 await self.close()891892 async def close(self) -> None:893 """894 Close the response and release the connection.895 Automatically called if the response body is read to completion.896 """897 if not self.is_closed:898 self.is_closed = True899 if self.on_close is not None:900 await self.on_close()901902903class Response(BaseResponse):904 def __init__(905 self,906 status_code: int,907 *,908 protocol: str = None,909 headers: HeaderTypes = None,Multipart support (#90)Tom Christiebefore adoption6a44b05
line 910why, one step back910 content: ResponseContent = None,http3 (#86)Tom Christiebefore adoptionc9747aa
lines 911–924why, one step back911 on_close: typing.Callable = None,912 request: Request = None,913 history: typing.List["BaseResponse"] = None,914 ):915 super().__init__(916 status_code=status_code,917 protocol=protocol,918 headers=headers,919 request=request,920 on_close=on_close,921 )922923 self.history = [] if history is None else list(history)924Multipart support (#90)Tom Christiebefore adoption6a44b05
line 925why, one step back925 if content is None or isinstance(content, bytes):http3 (#86)Tom Christiebefore adoptionc9747aa
lines 926–927why, one step back926 self.is_closed = True927 self.is_stream_consumed = TrueMultipart support (#90)Tom Christiebefore adoption6a44b05
line 928why, one step back928 self._raw_content = content or b""http3 (#86)Tom Christiebefore adoptionc9747aa
lines 929–1154why, one step back929 else:930 self.is_closed = False931 self.is_stream_consumed = False932 self._raw_stream = content933934 def read(self) -> bytes:935 """936 Read and return the response content.937 """938 if not hasattr(self, "_content"):939 self._content = b"".join([part for part in self.stream()])940 return self._content941942 def stream(self) -> typing.Iterator[bytes]:943 """944 A byte-iterator over the decoded response content.945 This allows us to handle gzip, deflate, and brotli encoded responses.946 """947 if hasattr(self, "_content"):948 yield self._content949 else:950 for chunk in self.raw():951 yield self.decoder.decode(chunk)952 yield self.decoder.flush()953954 def raw(self) -> typing.Iterator[bytes]:955 """956 A byte-iterator over the raw response content.957 """958 if hasattr(self, "_raw_content"):959 yield self._raw_content960 else:961 if self.is_stream_consumed:962 raise StreamConsumed()963 if self.is_closed:964 raise ResponseClosed()965966 self.is_stream_consumed = True967 for part in self._raw_stream:968 yield part969 self.close()970971 def close(self) -> None:972 """973 Close the response and release the connection.974 Automatically called if the response body is read to completion.975 """976 if not self.is_closed:977 self.is_closed = True978 if self.on_close is not None:979 self.on_close()980981982class Cookies(MutableMapping):983 """984 HTTP Cookies, as a mutable mapping.985 """986987 def __init__(self, cookies: CookieTypes = None) -> None:988 if cookies is None or isinstance(cookies, dict):989 self.jar = CookieJar()990 if isinstance(cookies, dict):991 for key, value in cookies.items():992 self.set(key, value)993 elif isinstance(cookies, Cookies):994 self.jar = CookieJar()995 for cookie in cookies.jar:996 self.jar.set_cookie(cookie)997 else:998 self.jar = cookies9991000 def extract_cookies(self, response: BaseResponse) -> None:1001 """1002 Loads any cookies based on the response `Set-Cookie` headers.1003 """1004 assert response.request is not None1005 urlib_response = self._CookieCompatResponse(response)1006 urllib_request = self._CookieCompatRequest(response.request)10071008 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore10091010 def set_cookie_header(self, request: BaseRequest) -> None:1011 """1012 Sets an appropriate 'Cookie:' HTTP header on the `Request`.1013 """1014 urllib_request = self._CookieCompatRequest(request)1015 self.jar.add_cookie_header(urllib_request)10161017 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:1018 """1019 Set a cookie value by name. May optionally include domain and path.1020 """1021 kwargs = dict(1022 version=0,1023 name=name,1024 value=value,1025 port=None,1026 port_specified=False,1027 domain=domain,1028 domain_specified=bool(domain),1029 domain_initial_dot=domain.startswith("."),1030 path=path,1031 path_specified=bool(path),1032 secure=False,1033 expires=None,1034 discard=True,1035 comment=None,1036 comment_url=None,1037 rest={"HttpOnly": None},1038 rfc2109=False,1039 )1040 cookie = Cookie(**kwargs) # type: ignore1041 self.jar.set_cookie(cookie)10421043 def get( # type: ignore1044 self, name: str, default: str = None, domain: str = None, path: str = None1045 ) -> typing.Optional[str]:1046 """1047 Get a cookie by name. May optionally include domain and path1048 in order to specify exactly which cookie to retrieve.1049 """1050 value = None1051 for cookie in self.jar:1052 if cookie.name == name:1053 if domain is None or cookie.domain == domain: # type: ignore1054 if path is None or cookie.path == path:1055 if value is not None:1056 message = f"Multiple cookies exist with name={name}"1057 raise CookieConflict(message)1058 value = cookie.value10591060 if value is None:1061 return default1062 return value10631064 def delete(self, name: str, domain: str = None, path: str = None) -> None:1065 """1066 Delete a cookie by name. May optionally include domain and path1067 in order to specify exactly which cookie to delete.1068 """1069 if domain is not None and path is not None:1070 return self.jar.clear(domain, path, name)10711072 remove = []1073 for cookie in self.jar:1074 if cookie.name == name:1075 if domain is None or cookie.domain == domain: # type: ignore1076 if path is None or cookie.path == path:1077 remove.append(cookie)10781079 for cookie in remove:1080 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore10811082 def clear(self, domain: str = None, path: str = None) -> None:1083 """1084 Delete all cookies. Optionally include a domain and path in1085 order to only delete a subset of all the cookies.1086 """1087 args = []1088 if domain is not None:1089 args.append(domain)1090 if path is not None:1091 assert domain is not None1092 args.append(path)1093 self.jar.clear(*args)10941095 def update(self, cookies: CookieTypes = None) -> None: # type: ignore1096 cookies = Cookies(cookies)1097 for cookie in cookies.jar:1098 self.jar.set_cookie(cookie)10991100 def __setitem__(self, name: str, value: str) -> None:1101 return self.set(name, value)11021103 def __getitem__(self, name: str) -> str:1104 value = self.get(name)1105 if value is None:1106 raise KeyError(name)1107 return value11081109 def __delitem__(self, name: str) -> None:1110 return self.delete(name)11111112 def __len__(self) -> int:1113 return len(self.jar)11141115 def __iter__(self) -> typing.Iterator[str]:1116 return (cookie.name for cookie in self.jar)11171118 def __bool__(self) -> bool:1119 for cookie in self.jar:1120 return True1121 return False11221123 class _CookieCompatRequest(urllib.request.Request):1124 """1125 Wraps a `Request` instance up in a compatability interface suitable1126 for use with `CookieJar` operations.1127 """11281129 def __init__(self, request: BaseRequest) -> None:1130 super().__init__(1131 url=str(request.url),1132 headers=dict(request.headers),1133 method=request.method,1134 )1135 self.request = request11361137 def add_unredirected_header(self, key: str, value: str) -> None:1138 super().add_unredirected_header(key, value)1139 self.request.headers[key] = value11401141 class _CookieCompatResponse:1142 """1143 Wraps a `Request` instance up in a compatability interface suitable1144 for use with `CookieJar` operations.1145 """11461147 def __init__(self, response: BaseResponse):1148 self.response = response11491150 def info(self) -> email.message.Message:1151 info = email.message.Message()1152 for key, value in self.response.headers.items():1153 info[key] = value1154 return info