_models.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. import datetime
  2. import email.message
  3. import json as jsonlib
  4. import typing
  5. import urllib.request
  6. from collections.abc import Mapping
  7. from http.cookiejar import Cookie, CookieJar
  8. from ._content import ByteStream, UnattachedStream, encode_request, encode_response
  9. from ._decoders import (
  10. SUPPORTED_DECODERS,
  11. ByteChunker,
  12. ContentDecoder,
  13. IdentityDecoder,
  14. LineDecoder,
  15. MultiDecoder,
  16. TextChunker,
  17. TextDecoder,
  18. )
  19. from ._exceptions import (
  20. CookieConflict,
  21. HTTPStatusError,
  22. RequestNotRead,
  23. ResponseNotRead,
  24. StreamClosed,
  25. StreamConsumed,
  26. request_context,
  27. )
  28. from ._multipart import get_multipart_boundary_from_content_type
  29. from ._status_codes import codes
  30. from ._types import (
  31. AsyncByteStream,
  32. CookieTypes,
  33. HeaderTypes,
  34. QueryParamTypes,
  35. RequestContent,
  36. RequestData,
  37. RequestExtensions,
  38. RequestFiles,
  39. ResponseContent,
  40. ResponseExtensions,
  41. SyncByteStream,
  42. )
  43. from ._urls import URL
  44. from ._utils import (
  45. is_known_encoding,
  46. normalize_header_key,
  47. normalize_header_value,
  48. obfuscate_sensitive_headers,
  49. parse_content_type_charset,
  50. parse_header_links,
  51. )
  52. class Headers(typing.MutableMapping[str, str]):
  53. """
  54. HTTP headers, as a case-insensitive multi-dict.
  55. """
  56. def __init__(
  57. self,
  58. headers: typing.Optional[HeaderTypes] = None,
  59. encoding: typing.Optional[str] = None,
  60. ) -> None:
  61. if headers is None:
  62. self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]]
  63. elif isinstance(headers, Headers):
  64. self._list = list(headers._list)
  65. elif isinstance(headers, Mapping):
  66. self._list = [
  67. (
  68. normalize_header_key(k, lower=False, encoding=encoding),
  69. normalize_header_key(k, lower=True, encoding=encoding),
  70. normalize_header_value(v, encoding),
  71. )
  72. for k, v in headers.items()
  73. ]
  74. else:
  75. self._list = [
  76. (
  77. normalize_header_key(k, lower=False, encoding=encoding),
  78. normalize_header_key(k, lower=True, encoding=encoding),
  79. normalize_header_value(v, encoding),
  80. )
  81. for k, v in headers
  82. ]
  83. self._encoding = encoding
  84. @property
  85. def encoding(self) -> str:
  86. """
  87. Header encoding is mandated as ascii, but we allow fallbacks to utf-8
  88. or iso-8859-1.
  89. """
  90. if self._encoding is None:
  91. for encoding in ["ascii", "utf-8"]:
  92. for key, value in self.raw:
  93. try:
  94. key.decode(encoding)
  95. value.decode(encoding)
  96. except UnicodeDecodeError:
  97. break
  98. else:
  99. # The else block runs if 'break' did not occur, meaning
  100. # all values fitted the encoding.
  101. self._encoding = encoding
  102. break
  103. else:
  104. # The ISO-8859-1 encoding covers all 256 code points in a byte,
  105. # so will never raise decode errors.
  106. self._encoding = "iso-8859-1"
  107. return self._encoding
  108. @encoding.setter
  109. def encoding(self, value: str) -> None:
  110. self._encoding = value
  111. @property
  112. def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:
  113. """
  114. Returns a list of the raw header items, as byte pairs.
  115. """
  116. return [(raw_key, value) for raw_key, _, value in self._list]
  117. def keys(self) -> typing.KeysView[str]:
  118. return {key.decode(self.encoding): None for _, key, value in self._list}.keys()
  119. def values(self) -> typing.ValuesView[str]:
  120. values_dict: typing.Dict[str, str] = {}
  121. for _, key, value in self._list:
  122. str_key = key.decode(self.encoding)
  123. str_value = value.decode(self.encoding)
  124. if str_key in values_dict:
  125. values_dict[str_key] += f", {str_value}"
  126. else:
  127. values_dict[str_key] = str_value
  128. return values_dict.values()
  129. def items(self) -> typing.ItemsView[str, str]:
  130. """
  131. Return `(key, value)` items of headers. Concatenate headers
  132. into a single comma separated value when a key occurs multiple times.
  133. """
  134. values_dict: typing.Dict[str, str] = {}
  135. for _, key, value in self._list:
  136. str_key = key.decode(self.encoding)
  137. str_value = value.decode(self.encoding)
  138. if str_key in values_dict:
  139. values_dict[str_key] += f", {str_value}"
  140. else:
  141. values_dict[str_key] = str_value
  142. return values_dict.items()
  143. def multi_items(self) -> typing.List[typing.Tuple[str, str]]:
  144. """
  145. Return a list of `(key, value)` pairs of headers. Allow multiple
  146. occurrences of the same key without concatenating into a single
  147. comma separated value.
  148. """
  149. return [
  150. (key.decode(self.encoding), value.decode(self.encoding))
  151. for _, key, value in self._list
  152. ]
  153. def get(self, key: str, default: typing.Any = None) -> typing.Any:
  154. """
  155. Return a header value. If multiple occurrences of the header occur
  156. then concatenate them together with commas.
  157. """
  158. try:
  159. return self[key]
  160. except KeyError:
  161. return default
  162. def get_list(self, key: str, split_commas: bool = False) -> typing.List[str]:
  163. """
  164. Return a list of all header values for a given key.
  165. If `split_commas=True` is passed, then any comma separated header
  166. values are split into multiple return strings.
  167. """
  168. get_header_key = key.lower().encode(self.encoding)
  169. values = [
  170. item_value.decode(self.encoding)
  171. for _, item_key, item_value in self._list
  172. if item_key.lower() == get_header_key
  173. ]
  174. if not split_commas:
  175. return values
  176. split_values = []
  177. for value in values:
  178. split_values.extend([item.strip() for item in value.split(",")])
  179. return split_values
  180. def update(self, headers: typing.Optional[HeaderTypes] = None) -> None: # type: ignore
  181. headers = Headers(headers)
  182. for key in headers.keys():
  183. if key in self:
  184. self.pop(key)
  185. self._list.extend(headers._list)
  186. def copy(self) -> "Headers":
  187. return Headers(self, encoding=self.encoding)
  188. def __getitem__(self, key: str) -> str:
  189. """
  190. Return a single header value.
  191. If there are multiple headers with the same key, then we concatenate
  192. them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2
  193. """
  194. normalized_key = key.lower().encode(self.encoding)
  195. items = [
  196. header_value.decode(self.encoding)
  197. for _, header_key, header_value in self._list
  198. if header_key == normalized_key
  199. ]
  200. if items:
  201. return ", ".join(items)
  202. raise KeyError(key)
  203. def __setitem__(self, key: str, value: str) -> None:
  204. """
  205. Set the header `key` to `value`, removing any duplicate entries.
  206. Retains insertion order.
  207. """
  208. set_key = key.encode(self._encoding or "utf-8")
  209. set_value = value.encode(self._encoding or "utf-8")
  210. lookup_key = set_key.lower()
  211. found_indexes = [
  212. idx
  213. for idx, (_, item_key, _) in enumerate(self._list)
  214. if item_key == lookup_key
  215. ]
  216. for idx in reversed(found_indexes[1:]):
  217. del self._list[idx]
  218. if found_indexes:
  219. idx = found_indexes[0]
  220. self._list[idx] = (set_key, lookup_key, set_value)
  221. else:
  222. self._list.append((set_key, lookup_key, set_value))
  223. def __delitem__(self, key: str) -> None:
  224. """
  225. Remove the header `key`.
  226. """
  227. del_key = key.lower().encode(self.encoding)
  228. pop_indexes = [
  229. idx
  230. for idx, (_, item_key, _) in enumerate(self._list)
  231. if item_key.lower() == del_key
  232. ]
  233. if not pop_indexes:
  234. raise KeyError(key)
  235. for idx in reversed(pop_indexes):
  236. del self._list[idx]
  237. def __contains__(self, key: typing.Any) -> bool:
  238. header_key = key.lower().encode(self.encoding)
  239. return header_key in [key for _, key, _ in self._list]
  240. def __iter__(self) -> typing.Iterator[typing.Any]:
  241. return iter(self.keys())
  242. def __len__(self) -> int:
  243. return len(self._list)
  244. def __eq__(self, other: typing.Any) -> bool:
  245. try:
  246. other_headers = Headers(other)
  247. except ValueError:
  248. return False
  249. self_list = [(key, value) for _, key, value in self._list]
  250. other_list = [(key, value) for _, key, value in other_headers._list]
  251. return sorted(self_list) == sorted(other_list)
  252. def __repr__(self) -> str:
  253. class_name = self.__class__.__name__
  254. encoding_str = ""
  255. if self.encoding != "ascii":
  256. encoding_str = f", encoding={self.encoding!r}"
  257. as_list = list(obfuscate_sensitive_headers(self.multi_items()))
  258. as_dict = dict(as_list)
  259. no_duplicate_keys = len(as_dict) == len(as_list)
  260. if no_duplicate_keys:
  261. return f"{class_name}({as_dict!r}{encoding_str})"
  262. return f"{class_name}({as_list!r}{encoding_str})"
  263. class Request:
  264. def __init__(
  265. self,
  266. method: typing.Union[str, bytes],
  267. url: typing.Union["URL", str],
  268. *,
  269. params: typing.Optional[QueryParamTypes] = None,
  270. headers: typing.Optional[HeaderTypes] = None,
  271. cookies: typing.Optional[CookieTypes] = None,
  272. content: typing.Optional[RequestContent] = None,
  273. data: typing.Optional[RequestData] = None,
  274. files: typing.Optional[RequestFiles] = None,
  275. json: typing.Optional[typing.Any] = None,
  276. stream: typing.Union[SyncByteStream, AsyncByteStream, None] = None,
  277. extensions: typing.Optional[RequestExtensions] = None,
  278. ):
  279. self.method = (
  280. method.decode("ascii").upper()
  281. if isinstance(method, bytes)
  282. else method.upper()
  283. )
  284. self.url = URL(url)
  285. if params is not None:
  286. self.url = self.url.copy_merge_params(params=params)
  287. self.headers = Headers(headers)
  288. self.extensions = {} if extensions is None else extensions
  289. if cookies:
  290. Cookies(cookies).set_cookie_header(self)
  291. if stream is None:
  292. content_type: typing.Optional[str] = self.headers.get("content-type")
  293. headers, stream = encode_request(
  294. content=content,
  295. data=data,
  296. files=files,
  297. json=json,
  298. boundary=get_multipart_boundary_from_content_type(
  299. content_type=content_type.encode(self.headers.encoding)
  300. if content_type
  301. else None
  302. ),
  303. )
  304. self._prepare(headers)
  305. self.stream = stream
  306. # Load the request body, except for streaming content.
  307. if isinstance(stream, ByteStream):
  308. self.read()
  309. else:
  310. # There's an important distinction between `Request(content=...)`,
  311. # and `Request(stream=...)`.
  312. #
  313. # Using `content=...` implies automatically populated `Host` and content
  314. # headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`.
  315. #
  316. # Using `stream=...` will not automatically include *any* auto-populated headers.
  317. #
  318. # As an end-user you don't really need `stream=...`. It's only
  319. # useful when:
  320. #
  321. # * Preserving the request stream when copying requests, eg for redirects.
  322. # * Creating request instances on the *server-side* of the transport API.
  323. self.stream = stream
  324. def _prepare(self, default_headers: typing.Dict[str, str]) -> None:
  325. for key, value in default_headers.items():
  326. # Ignore Transfer-Encoding if the Content-Length has been set explicitly.
  327. if key.lower() == "transfer-encoding" and "Content-Length" in self.headers:
  328. continue
  329. self.headers.setdefault(key, value)
  330. auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []
  331. has_host = "Host" in self.headers
  332. has_content_length = (
  333. "Content-Length" in self.headers or "Transfer-Encoding" in self.headers
  334. )
  335. if not has_host and self.url.host:
  336. auto_headers.append((b"Host", self.url.netloc))
  337. if not has_content_length and self.method in ("POST", "PUT", "PATCH"):
  338. auto_headers.append((b"Content-Length", b"0"))
  339. self.headers = Headers(auto_headers + self.headers.raw)
  340. @property
  341. def content(self) -> bytes:
  342. if not hasattr(self, "_content"):
  343. raise RequestNotRead()
  344. return self._content
  345. def read(self) -> bytes:
  346. """
  347. Read and return the request content.
  348. """
  349. if not hasattr(self, "_content"):
  350. assert isinstance(self.stream, typing.Iterable)
  351. self._content = b"".join(self.stream)
  352. if not isinstance(self.stream, ByteStream):
  353. # If a streaming request has been read entirely into memory, then
  354. # we can replace the stream with a raw bytes implementation,
  355. # to ensure that any non-replayable streams can still be used.
  356. self.stream = ByteStream(self._content)
  357. return self._content
  358. async def aread(self) -> bytes:
  359. """
  360. Read and return the request content.
  361. """
  362. if not hasattr(self, "_content"):
  363. assert isinstance(self.stream, typing.AsyncIterable)
  364. self._content = b"".join([part async for part in self.stream])
  365. if not isinstance(self.stream, ByteStream):
  366. # If a streaming request has been read entirely into memory, then
  367. # we can replace the stream with a raw bytes implementation,
  368. # to ensure that any non-replayable streams can still be used.
  369. self.stream = ByteStream(self._content)
  370. return self._content
  371. def __repr__(self) -> str:
  372. class_name = self.__class__.__name__
  373. url = str(self.url)
  374. return f"<{class_name}({self.method!r}, {url!r})>"
  375. def __getstate__(self) -> typing.Dict[str, typing.Any]:
  376. return {
  377. name: value
  378. for name, value in self.__dict__.items()
  379. if name not in ["extensions", "stream"]
  380. }
  381. def __setstate__(self, state: typing.Dict[str, typing.Any]) -> None:
  382. for name, value in state.items():
  383. setattr(self, name, value)
  384. self.extensions = {}
  385. self.stream = UnattachedStream()
  386. class Response:
  387. def __init__(
  388. self,
  389. status_code: int,
  390. *,
  391. headers: typing.Optional[HeaderTypes] = None,
  392. content: typing.Optional[ResponseContent] = None,
  393. text: typing.Optional[str] = None,
  394. html: typing.Optional[str] = None,
  395. json: typing.Any = None,
  396. stream: typing.Union[SyncByteStream, AsyncByteStream, None] = None,
  397. request: typing.Optional[Request] = None,
  398. extensions: typing.Optional[ResponseExtensions] = None,
  399. history: typing.Optional[typing.List["Response"]] = None,
  400. default_encoding: typing.Union[str, typing.Callable[[bytes], str]] = "utf-8",
  401. ):
  402. self.status_code = status_code
  403. self.headers = Headers(headers)
  404. self._request: typing.Optional[Request] = request
  405. # When follow_redirects=False and a redirect is received,
  406. # the client will set `response.next_request`.
  407. self.next_request: typing.Optional[Request] = None
  408. self.extensions: ResponseExtensions = {} if extensions is None else extensions
  409. self.history = [] if history is None else list(history)
  410. self.is_closed = False
  411. self.is_stream_consumed = False
  412. self.default_encoding = default_encoding
  413. if stream is None:
  414. headers, stream = encode_response(content, text, html, json)
  415. self._prepare(headers)
  416. self.stream = stream
  417. if isinstance(stream, ByteStream):
  418. # Load the response body, except for streaming content.
  419. self.read()
  420. else:
  421. # There's an important distinction between `Response(content=...)`,
  422. # and `Response(stream=...)`.
  423. #
  424. # Using `content=...` implies automatically populated content headers,
  425. # of either `Content-Length: ...` or `Transfer-Encoding: chunked`.
  426. #
  427. # Using `stream=...` will not automatically include any content headers.
  428. #
  429. # As an end-user you don't really need `stream=...`. It's only
  430. # useful when creating response instances having received a stream
  431. # from the transport API.
  432. self.stream = stream
  433. self._num_bytes_downloaded = 0
  434. def _prepare(self, default_headers: typing.Dict[str, str]) -> None:
  435. for key, value in default_headers.items():
  436. # Ignore Transfer-Encoding if the Content-Length has been set explicitly.
  437. if key.lower() == "transfer-encoding" and "content-length" in self.headers:
  438. continue
  439. self.headers.setdefault(key, value)
  440. @property
  441. def elapsed(self) -> datetime.timedelta:
  442. """
  443. Returns the time taken for the complete request/response
  444. cycle to complete.
  445. """
  446. if not hasattr(self, "_elapsed"):
  447. raise RuntimeError(
  448. "'.elapsed' may only be accessed after the response "
  449. "has been read or closed."
  450. )
  451. return self._elapsed
  452. @elapsed.setter
  453. def elapsed(self, elapsed: datetime.timedelta) -> None:
  454. self._elapsed = elapsed
  455. @property
  456. def request(self) -> Request:
  457. """
  458. Returns the request instance associated to the current response.
  459. """
  460. if self._request is None:
  461. raise RuntimeError(
  462. "The request instance has not been set on this response."
  463. )
  464. return self._request
  465. @request.setter
  466. def request(self, value: Request) -> None:
  467. self._request = value
  468. @property
  469. def http_version(self) -> str:
  470. try:
  471. http_version: bytes = self.extensions["http_version"]
  472. except KeyError:
  473. return "HTTP/1.1"
  474. else:
  475. return http_version.decode("ascii", errors="ignore")
  476. @property
  477. def reason_phrase(self) -> str:
  478. try:
  479. reason_phrase: bytes = self.extensions["reason_phrase"]
  480. except KeyError:
  481. return codes.get_reason_phrase(self.status_code)
  482. else:
  483. return reason_phrase.decode("ascii", errors="ignore")
  484. @property
  485. def url(self) -> URL:
  486. """
  487. Returns the URL for which the request was made.
  488. """
  489. return self.request.url
  490. @property
  491. def content(self) -> bytes:
  492. if not hasattr(self, "_content"):
  493. raise ResponseNotRead()
  494. return self._content
  495. @property
  496. def text(self) -> str:
  497. if not hasattr(self, "_text"):
  498. content = self.content
  499. if not content:
  500. self._text = ""
  501. else:
  502. decoder = TextDecoder(encoding=self.encoding or "utf-8")
  503. self._text = "".join([decoder.decode(self.content), decoder.flush()])
  504. return self._text
  505. @property
  506. def encoding(self) -> typing.Optional[str]:
  507. """
  508. Return an encoding to use for decoding the byte content into text.
  509. The priority for determining this is given by...
  510. * `.encoding = <>` has been set explicitly.
  511. * The encoding as specified by the charset parameter in the Content-Type header.
  512. * The encoding as determined by `default_encoding`, which may either be
  513. a string like "utf-8" indicating the encoding to use, or may be a callable
  514. which enables charset autodetection.
  515. """
  516. if not hasattr(self, "_encoding"):
  517. encoding = self.charset_encoding
  518. if encoding is None or not is_known_encoding(encoding):
  519. if isinstance(self.default_encoding, str):
  520. encoding = self.default_encoding
  521. elif hasattr(self, "_content"):
  522. encoding = self.default_encoding(self._content)
  523. self._encoding = encoding or "utf-8"
  524. return self._encoding
  525. @encoding.setter
  526. def encoding(self, value: str) -> None:
  527. """
  528. Set the encoding to use for decoding the byte content into text.
  529. If the `text` attribute has been accessed, attempting to set the
  530. encoding will throw a ValueError.
  531. """
  532. if hasattr(self, "_text"):
  533. raise ValueError(
  534. "Setting encoding after `text` has been accessed is not allowed."
  535. )
  536. self._encoding = value
  537. @property
  538. def charset_encoding(self) -> typing.Optional[str]:
  539. """
  540. Return the encoding, as specified by the Content-Type header.
  541. """
  542. content_type = self.headers.get("Content-Type")
  543. if content_type is None:
  544. return None
  545. return parse_content_type_charset(content_type)
  546. def _get_content_decoder(self) -> ContentDecoder:
  547. """
  548. Returns a decoder instance which can be used to decode the raw byte
  549. content, depending on the Content-Encoding used in the response.
  550. """
  551. if not hasattr(self, "_decoder"):
  552. decoders: typing.List[ContentDecoder] = []
  553. values = self.headers.get_list("content-encoding", split_commas=True)
  554. for value in values:
  555. value = value.strip().lower()
  556. try:
  557. decoder_cls = SUPPORTED_DECODERS[value]
  558. decoders.append(decoder_cls())
  559. except KeyError:
  560. continue
  561. if len(decoders) == 1:
  562. self._decoder = decoders[0]
  563. elif len(decoders) > 1:
  564. self._decoder = MultiDecoder(children=decoders)
  565. else:
  566. self._decoder = IdentityDecoder()
  567. return self._decoder
  568. @property
  569. def is_informational(self) -> bool:
  570. """
  571. A property which is `True` for 1xx status codes, `False` otherwise.
  572. """
  573. return codes.is_informational(self.status_code)
  574. @property
  575. def is_success(self) -> bool:
  576. """
  577. A property which is `True` for 2xx status codes, `False` otherwise.
  578. """
  579. return codes.is_success(self.status_code)
  580. @property
  581. def is_redirect(self) -> bool:
  582. """
  583. A property which is `True` for 3xx status codes, `False` otherwise.
  584. Note that not all responses with a 3xx status code indicate a URL redirect.
  585. Use `response.has_redirect_location` to determine responses with a properly
  586. formed URL redirection.
  587. """
  588. return codes.is_redirect(self.status_code)
  589. @property
  590. def is_client_error(self) -> bool:
  591. """
  592. A property which is `True` for 4xx status codes, `False` otherwise.
  593. """
  594. return codes.is_client_error(self.status_code)
  595. @property
  596. def is_server_error(self) -> bool:
  597. """
  598. A property which is `True` for 5xx status codes, `False` otherwise.
  599. """
  600. return codes.is_server_error(self.status_code)
  601. @property
  602. def is_error(self) -> bool:
  603. """
  604. A property which is `True` for 4xx and 5xx status codes, `False` otherwise.
  605. """
  606. return codes.is_error(self.status_code)
  607. @property
  608. def has_redirect_location(self) -> bool:
  609. """
  610. Returns True for 3xx responses with a properly formed URL redirection,
  611. `False` otherwise.
  612. """
  613. return (
  614. self.status_code
  615. in (
  616. # 301 (Cacheable redirect. Method may change to GET.)
  617. codes.MOVED_PERMANENTLY,
  618. # 302 (Uncacheable redirect. Method may change to GET.)
  619. codes.FOUND,
  620. # 303 (Client should make a GET or HEAD request.)
  621. codes.SEE_OTHER,
  622. # 307 (Equiv. 302, but retain method)
  623. codes.TEMPORARY_REDIRECT,
  624. # 308 (Equiv. 301, but retain method)
  625. codes.PERMANENT_REDIRECT,
  626. )
  627. and "Location" in self.headers
  628. )
  629. def raise_for_status(self) -> "Response":
  630. """
  631. Raise the `HTTPStatusError` if one occurred.
  632. """
  633. request = self._request
  634. if request is None:
  635. raise RuntimeError(
  636. "Cannot call `raise_for_status` as the request "
  637. "instance has not been set on this response."
  638. )
  639. if self.is_success:
  640. return self
  641. if self.has_redirect_location:
  642. message = (
  643. "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n"
  644. "Redirect location: '{0.headers[location]}'\n"
  645. "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}"
  646. )
  647. else:
  648. message = (
  649. "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n"
  650. "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}"
  651. )
  652. status_class = self.status_code // 100
  653. error_types = {
  654. 1: "Informational response",
  655. 3: "Redirect response",
  656. 4: "Client error",
  657. 5: "Server error",
  658. }
  659. error_type = error_types.get(status_class, "Invalid status code")
  660. message = message.format(self, error_type=error_type)
  661. raise HTTPStatusError(message, request=request, response=self)
  662. def json(self, **kwargs: typing.Any) -> typing.Any:
  663. return jsonlib.loads(self.content, **kwargs)
  664. @property
  665. def cookies(self) -> "Cookies":
  666. if not hasattr(self, "_cookies"):
  667. self._cookies = Cookies()
  668. self._cookies.extract_cookies(self)
  669. return self._cookies
  670. @property
  671. def links(self) -> typing.Dict[typing.Optional[str], typing.Dict[str, str]]:
  672. """
  673. Returns the parsed header links of the response, if any
  674. """
  675. header = self.headers.get("link")
  676. ldict = {}
  677. if header:
  678. links = parse_header_links(header)
  679. for link in links:
  680. key = link.get("rel") or link.get("url")
  681. ldict[key] = link
  682. return ldict
  683. @property
  684. def num_bytes_downloaded(self) -> int:
  685. return self._num_bytes_downloaded
  686. def __repr__(self) -> str:
  687. return f"<Response [{self.status_code} {self.reason_phrase}]>"
  688. def __getstate__(self) -> typing.Dict[str, typing.Any]:
  689. return {
  690. name: value
  691. for name, value in self.__dict__.items()
  692. if name not in ["extensions", "stream", "is_closed", "_decoder"]
  693. }
  694. def __setstate__(self, state: typing.Dict[str, typing.Any]) -> None:
  695. for name, value in state.items():
  696. setattr(self, name, value)
  697. self.is_closed = True
  698. self.extensions = {}
  699. self.stream = UnattachedStream()
  700. def read(self) -> bytes:
  701. """
  702. Read and return the response content.
  703. """
  704. if not hasattr(self, "_content"):
  705. self._content = b"".join(self.iter_bytes())
  706. return self._content
  707. def iter_bytes(
  708. self, chunk_size: typing.Optional[int] = None
  709. ) -> typing.Iterator[bytes]:
  710. """
  711. A byte-iterator over the decoded response content.
  712. This allows us to handle gzip, deflate, and brotli encoded responses.
  713. """
  714. if hasattr(self, "_content"):
  715. chunk_size = len(self._content) if chunk_size is None else chunk_size
  716. for i in range(0, len(self._content), max(chunk_size, 1)):
  717. yield self._content[i : i + chunk_size]
  718. else:
  719. decoder = self._get_content_decoder()
  720. chunker = ByteChunker(chunk_size=chunk_size)
  721. with request_context(request=self._request):
  722. for raw_bytes in self.iter_raw():
  723. decoded = decoder.decode(raw_bytes)
  724. for chunk in chunker.decode(decoded):
  725. yield chunk
  726. decoded = decoder.flush()
  727. for chunk in chunker.decode(decoded):
  728. yield chunk # pragma: no cover
  729. for chunk in chunker.flush():
  730. yield chunk
  731. def iter_text(
  732. self, chunk_size: typing.Optional[int] = None
  733. ) -> typing.Iterator[str]:
  734. """
  735. A str-iterator over the decoded response content
  736. that handles both gzip, deflate, etc but also detects the content's
  737. string encoding.
  738. """
  739. decoder = TextDecoder(encoding=self.encoding or "utf-8")
  740. chunker = TextChunker(chunk_size=chunk_size)
  741. with request_context(request=self._request):
  742. for byte_content in self.iter_bytes():
  743. text_content = decoder.decode(byte_content)
  744. for chunk in chunker.decode(text_content):
  745. yield chunk
  746. text_content = decoder.flush()
  747. for chunk in chunker.decode(text_content):
  748. yield chunk
  749. for chunk in chunker.flush():
  750. yield chunk
  751. def iter_lines(self) -> typing.Iterator[str]:
  752. decoder = LineDecoder()
  753. with request_context(request=self._request):
  754. for text in self.iter_text():
  755. for line in decoder.decode(text):
  756. yield line
  757. for line in decoder.flush():
  758. yield line
  759. def iter_raw(
  760. self, chunk_size: typing.Optional[int] = None
  761. ) -> typing.Iterator[bytes]:
  762. """
  763. A byte-iterator over the raw response content.
  764. """
  765. if self.is_stream_consumed:
  766. raise StreamConsumed()
  767. if self.is_closed:
  768. raise StreamClosed()
  769. if not isinstance(self.stream, SyncByteStream):
  770. raise RuntimeError("Attempted to call a sync iterator on an async stream.")
  771. self.is_stream_consumed = True
  772. self._num_bytes_downloaded = 0
  773. chunker = ByteChunker(chunk_size=chunk_size)
  774. with request_context(request=self._request):
  775. for raw_stream_bytes in self.stream:
  776. self._num_bytes_downloaded += len(raw_stream_bytes)
  777. for chunk in chunker.decode(raw_stream_bytes):
  778. yield chunk
  779. for chunk in chunker.flush():
  780. yield chunk
  781. self.close()
  782. def close(self) -> None:
  783. """
  784. Close the response and release the connection.
  785. Automatically called if the response body is read to completion.
  786. """
  787. if not isinstance(self.stream, SyncByteStream):
  788. raise RuntimeError("Attempted to call an sync close on an async stream.")
  789. if not self.is_closed:
  790. self.is_closed = True
  791. with request_context(request=self._request):
  792. self.stream.close()
  793. async def aread(self) -> bytes:
  794. """
  795. Read and return the response content.
  796. """
  797. if not hasattr(self, "_content"):
  798. self._content = b"".join([part async for part in self.aiter_bytes()])
  799. return self._content
  800. async def aiter_bytes(
  801. self, chunk_size: typing.Optional[int] = None
  802. ) -> typing.AsyncIterator[bytes]:
  803. """
  804. A byte-iterator over the decoded response content.
  805. This allows us to handle gzip, deflate, and brotli encoded responses.
  806. """
  807. if hasattr(self, "_content"):
  808. chunk_size = len(self._content) if chunk_size is None else chunk_size
  809. for i in range(0, len(self._content), max(chunk_size, 1)):
  810. yield self._content[i : i + chunk_size]
  811. else:
  812. decoder = self._get_content_decoder()
  813. chunker = ByteChunker(chunk_size=chunk_size)
  814. with request_context(request=self._request):
  815. async for raw_bytes in self.aiter_raw():
  816. decoded = decoder.decode(raw_bytes)
  817. for chunk in chunker.decode(decoded):
  818. yield chunk
  819. decoded = decoder.flush()
  820. for chunk in chunker.decode(decoded):
  821. yield chunk # pragma: no cover
  822. for chunk in chunker.flush():
  823. yield chunk
  824. async def aiter_text(
  825. self, chunk_size: typing.Optional[int] = None
  826. ) -> typing.AsyncIterator[str]:
  827. """
  828. A str-iterator over the decoded response content
  829. that handles both gzip, deflate, etc but also detects the content's
  830. string encoding.
  831. """
  832. decoder = TextDecoder(encoding=self.encoding or "utf-8")
  833. chunker = TextChunker(chunk_size=chunk_size)
  834. with request_context(request=self._request):
  835. async for byte_content in self.aiter_bytes():
  836. text_content = decoder.decode(byte_content)
  837. for chunk in chunker.decode(text_content):
  838. yield chunk
  839. text_content = decoder.flush()
  840. for chunk in chunker.decode(text_content):
  841. yield chunk
  842. for chunk in chunker.flush():
  843. yield chunk
  844. async def aiter_lines(self) -> typing.AsyncIterator[str]:
  845. decoder = LineDecoder()
  846. with request_context(request=self._request):
  847. async for text in self.aiter_text():
  848. for line in decoder.decode(text):
  849. yield line
  850. for line in decoder.flush():
  851. yield line
  852. async def aiter_raw(
  853. self, chunk_size: typing.Optional[int] = None
  854. ) -> typing.AsyncIterator[bytes]:
  855. """
  856. A byte-iterator over the raw response content.
  857. """
  858. if self.is_stream_consumed:
  859. raise StreamConsumed()
  860. if self.is_closed:
  861. raise StreamClosed()
  862. if not isinstance(self.stream, AsyncByteStream):
  863. raise RuntimeError("Attempted to call an async iterator on an sync stream.")
  864. self.is_stream_consumed = True
  865. self._num_bytes_downloaded = 0
  866. chunker = ByteChunker(chunk_size=chunk_size)
  867. with request_context(request=self._request):
  868. async for raw_stream_bytes in self.stream:
  869. self._num_bytes_downloaded += len(raw_stream_bytes)
  870. for chunk in chunker.decode(raw_stream_bytes):
  871. yield chunk
  872. for chunk in chunker.flush():
  873. yield chunk
  874. await self.aclose()
  875. async def aclose(self) -> None:
  876. """
  877. Close the response and release the connection.
  878. Automatically called if the response body is read to completion.
  879. """
  880. if not isinstance(self.stream, AsyncByteStream):
  881. raise RuntimeError("Attempted to call an async close on an sync stream.")
  882. if not self.is_closed:
  883. self.is_closed = True
  884. with request_context(request=self._request):
  885. await self.stream.aclose()
  886. class Cookies(typing.MutableMapping[str, str]):
  887. """
  888. HTTP Cookies, as a mutable mapping.
  889. """
  890. def __init__(self, cookies: typing.Optional[CookieTypes] = None) -> None:
  891. if cookies is None or isinstance(cookies, dict):
  892. self.jar = CookieJar()
  893. if isinstance(cookies, dict):
  894. for key, value in cookies.items():
  895. self.set(key, value)
  896. elif isinstance(cookies, list):
  897. self.jar = CookieJar()
  898. for key, value in cookies:
  899. self.set(key, value)
  900. elif isinstance(cookies, Cookies):
  901. self.jar = CookieJar()
  902. for cookie in cookies.jar:
  903. self.jar.set_cookie(cookie)
  904. else:
  905. self.jar = cookies
  906. def extract_cookies(self, response: Response) -> None:
  907. """
  908. Loads any cookies based on the response `Set-Cookie` headers.
  909. """
  910. urllib_response = self._CookieCompatResponse(response)
  911. urllib_request = self._CookieCompatRequest(response.request)
  912. self.jar.extract_cookies(urllib_response, urllib_request) # type: ignore
  913. def set_cookie_header(self, request: Request) -> None:
  914. """
  915. Sets an appropriate 'Cookie:' HTTP header on the `Request`.
  916. """
  917. urllib_request = self._CookieCompatRequest(request)
  918. self.jar.add_cookie_header(urllib_request)
  919. def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:
  920. """
  921. Set a cookie value by name. May optionally include domain and path.
  922. """
  923. kwargs = {
  924. "version": 0,
  925. "name": name,
  926. "value": value,
  927. "port": None,
  928. "port_specified": False,
  929. "domain": domain,
  930. "domain_specified": bool(domain),
  931. "domain_initial_dot": domain.startswith("."),
  932. "path": path,
  933. "path_specified": bool(path),
  934. "secure": False,
  935. "expires": None,
  936. "discard": True,
  937. "comment": None,
  938. "comment_url": None,
  939. "rest": {"HttpOnly": None},
  940. "rfc2109": False,
  941. }
  942. cookie = Cookie(**kwargs) # type: ignore
  943. self.jar.set_cookie(cookie)
  944. def get( # type: ignore
  945. self,
  946. name: str,
  947. default: typing.Optional[str] = None,
  948. domain: typing.Optional[str] = None,
  949. path: typing.Optional[str] = None,
  950. ) -> typing.Optional[str]:
  951. """
  952. Get a cookie by name. May optionally include domain and path
  953. in order to specify exactly which cookie to retrieve.
  954. """
  955. value = None
  956. for cookie in self.jar:
  957. if cookie.name == name:
  958. if domain is None or cookie.domain == domain:
  959. if path is None or cookie.path == path:
  960. if value is not None:
  961. message = f"Multiple cookies exist with name={name}"
  962. raise CookieConflict(message)
  963. value = cookie.value
  964. if value is None:
  965. return default
  966. return value
  967. def delete(
  968. self,
  969. name: str,
  970. domain: typing.Optional[str] = None,
  971. path: typing.Optional[str] = None,
  972. ) -> None:
  973. """
  974. Delete a cookie by name. May optionally include domain and path
  975. in order to specify exactly which cookie to delete.
  976. """
  977. if domain is not None and path is not None:
  978. return self.jar.clear(domain, path, name)
  979. remove = [
  980. cookie
  981. for cookie in self.jar
  982. if cookie.name == name
  983. and (domain is None or cookie.domain == domain)
  984. and (path is None or cookie.path == path)
  985. ]
  986. for cookie in remove:
  987. self.jar.clear(cookie.domain, cookie.path, cookie.name)
  988. def clear(
  989. self, domain: typing.Optional[str] = None, path: typing.Optional[str] = None
  990. ) -> None:
  991. """
  992. Delete all cookies. Optionally include a domain and path in
  993. order to only delete a subset of all the cookies.
  994. """
  995. args = []
  996. if domain is not None:
  997. args.append(domain)
  998. if path is not None:
  999. assert domain is not None
  1000. args.append(path)
  1001. self.jar.clear(*args)
  1002. def update(self, cookies: typing.Optional[CookieTypes] = None) -> None: # type: ignore
  1003. cookies = Cookies(cookies)
  1004. for cookie in cookies.jar:
  1005. self.jar.set_cookie(cookie)
  1006. def __setitem__(self, name: str, value: str) -> None:
  1007. return self.set(name, value)
  1008. def __getitem__(self, name: str) -> str:
  1009. value = self.get(name)
  1010. if value is None:
  1011. raise KeyError(name)
  1012. return value
  1013. def __delitem__(self, name: str) -> None:
  1014. return self.delete(name)
  1015. def __len__(self) -> int:
  1016. return len(self.jar)
  1017. def __iter__(self) -> typing.Iterator[str]:
  1018. return (cookie.name for cookie in self.jar)
  1019. def __bool__(self) -> bool:
  1020. for _ in self.jar:
  1021. return True
  1022. return False
  1023. def __repr__(self) -> str:
  1024. cookies_repr = ", ".join(
  1025. [
  1026. f"<Cookie {cookie.name}={cookie.value} for {cookie.domain} />"
  1027. for cookie in self.jar
  1028. ]
  1029. )
  1030. return f"<Cookies[{cookies_repr}]>"
  1031. class _CookieCompatRequest(urllib.request.Request):
  1032. """
  1033. Wraps a `Request` instance up in a compatibility interface suitable
  1034. for use with `CookieJar` operations.
  1035. """
  1036. def __init__(self, request: Request) -> None:
  1037. super().__init__(
  1038. url=str(request.url),
  1039. headers=dict(request.headers),
  1040. method=request.method,
  1041. )
  1042. self.request = request
  1043. def add_unredirected_header(self, key: str, value: str) -> None:
  1044. super().add_unredirected_header(key, value)
  1045. self.request.headers[key] = value
  1046. class _CookieCompatResponse:
  1047. """
  1048. Wraps a `Request` instance up in a compatibility interface suitable
  1049. for use with `CookieJar` operations.
  1050. """
  1051. def __init__(self, response: Response):
  1052. self.response = response
  1053. def info(self) -> email.message.Message:
  1054. info = email.message.Message()
  1055. for key, value in self.response.headers.multi_items():
  1056. # Note that setting `info[key]` here is an "append" operation,
  1057. # not a "replace" operation.
  1058. # https://docs.python.org/3/library/email.compat32-message.html#email.message.Message.__setitem__
  1059. info[key] = value
  1060. return info