models.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. """
  2. requests.models
  3. ~~~~~~~~~~~~~~~
  4. This module contains the primary objects that power Requests.
  5. """
  6. from __future__ import annotations
  7. import datetime
  8. # Import encoding now, to avoid implicit import later.
  9. # Implicit import within threads may cause LookupError when standard library is in a ZIP,
  10. # such as in Embedded Python. See https://github.com/psf/requests/issues/3578.
  11. import encodings.idna # noqa: F401 # type: ignore[reportUnusedImport]
  12. from collections.abc import Callable, Generator, Iterable, Iterator, Mapping
  13. from io import UnsupportedOperation
  14. from typing import (
  15. TYPE_CHECKING,
  16. Any,
  17. Final,
  18. Literal,
  19. cast,
  20. overload,
  21. )
  22. from urllib3.exceptions import (
  23. DecodeError,
  24. LocationParseError,
  25. ProtocolError,
  26. ReadTimeoutError,
  27. SSLError,
  28. )
  29. from urllib3.fields import RequestField
  30. from urllib3.filepost import encode_multipart_formdata
  31. from urllib3.util import parse_url
  32. from ._internal_utils import to_native_string, unicode_is_ascii
  33. from ._types import SupportsRead as _SupportsRead
  34. from .auth import HTTPBasicAuth
  35. from .compat import (
  36. JSONDecodeError,
  37. basestring,
  38. builtin_str,
  39. chardet,
  40. cookielib,
  41. urlencode,
  42. urlsplit,
  43. urlunparse,
  44. )
  45. from .compat import json as complexjson
  46. from .cookies import (
  47. _copy_cookie_jar, # type: ignore[reportPrivateUsage]
  48. cookiejar_from_dict,
  49. get_cookie_header,
  50. )
  51. from .exceptions import (
  52. ChunkedEncodingError,
  53. ConnectionError,
  54. ContentDecodingError,
  55. HTTPError,
  56. InvalidJSONError,
  57. InvalidURL,
  58. MissingSchema,
  59. StreamConsumedError,
  60. )
  61. from .exceptions import JSONDecodeError as RequestsJSONDecodeError
  62. from .exceptions import SSLError as RequestsSSLError
  63. from .hooks import default_hooks
  64. from .status_codes import codes
  65. from .structures import CaseInsensitiveDict
  66. from .utils import (
  67. check_header_validity,
  68. get_auth_from_url,
  69. guess_filename,
  70. guess_json_utf,
  71. iter_slices,
  72. parse_header_links,
  73. requote_uri,
  74. stream_decode_response_unicode,
  75. super_len,
  76. to_key_val_list,
  77. )
  78. if TYPE_CHECKING:
  79. from http.cookiejar import CookieJar
  80. from typing_extensions import Self
  81. from . import _types as _t
  82. from .adapters import HTTPAdapter
  83. from .cookies import RequestsCookieJar
  84. #: The set of HTTP status codes that indicate an automatically
  85. #: processable redirect.
  86. REDIRECT_STATI: Final[tuple[int, ...]] = ( # type: ignore[assignment]
  87. codes.moved, # 301
  88. codes.found, # 302
  89. codes.other, # 303
  90. codes.temporary_redirect, # 307
  91. codes.permanent_redirect, # 308
  92. )
  93. DEFAULT_REDIRECT_LIMIT: int = 30
  94. CONTENT_CHUNK_SIZE: int = 10 * 1024
  95. ITER_CHUNK_SIZE: int = 512
  96. class RequestEncodingMixin:
  97. url: str | None
  98. @property
  99. def path_url(self) -> str:
  100. """Build the path URL to use."""
  101. url: list[str] = []
  102. p = urlsplit(cast(str, self.url))
  103. path = p.path
  104. if not path:
  105. path = "/"
  106. url.append(path)
  107. query = p.query
  108. if query:
  109. url.append("?")
  110. url.append(query)
  111. return "".join(url)
  112. @overload
  113. @staticmethod
  114. def _encode_params(data: str) -> str: ...
  115. @overload
  116. @staticmethod
  117. def _encode_params(data: bytes) -> bytes: ...
  118. @overload
  119. @staticmethod
  120. def _encode_params(
  121. data: _t.SupportsRead[str | bytes],
  122. ) -> _t.SupportsRead[str | bytes]: ...
  123. @overload
  124. @staticmethod
  125. def _encode_params(data: _t.KVDataType) -> str: ...
  126. @staticmethod
  127. def _encode_params(
  128. data: _t.EncodableDataType,
  129. ) -> str | bytes | _t.SupportsRead[str | bytes]:
  130. """Encode parameters in a piece of data.
  131. Will successfully encode parameters when passed as a dict or a list of
  132. 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
  133. if parameters are supplied as a dict.
  134. """
  135. if isinstance(data, (str, bytes)):
  136. return data
  137. elif isinstance(data, _SupportsRead):
  138. return data
  139. elif hasattr(data, "__iter__"):
  140. result: list[tuple[bytes, bytes]] = []
  141. for k, vs in to_key_val_list(data):
  142. if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):
  143. vs = [vs]
  144. for v in vs:
  145. if v is not None:
  146. result.append(
  147. (
  148. k.encode("utf-8") if isinstance(k, str) else k,
  149. v.encode("utf-8") if isinstance(v, str) else v,
  150. )
  151. )
  152. return urlencode(result, doseq=True)
  153. else:
  154. return data # type: ignore[return-value] # unreachable for valid _t.DataType
  155. @staticmethod
  156. def _encode_files(
  157. files: _t.FilesType, data: _t.RawDataType | None
  158. ) -> tuple[bytes, str]:
  159. """Build the body for a multipart/form-data request.
  160. Will successfully encode files when passed as a dict or a list of
  161. tuples. Order is retained if data is a list of tuples but arbitrary
  162. if parameters are supplied as a dict.
  163. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
  164. or 4-tuples (filename, fileobj, contentype, custom_headers).
  165. """
  166. if not files:
  167. raise ValueError("Files must be provided.")
  168. elif isinstance(data, basestring):
  169. raise ValueError("Data must not be a string.")
  170. new_fields: list[RequestField | tuple[str, bytes]] = []
  171. fields = to_key_val_list(data or {})
  172. files = to_key_val_list(files or {})
  173. for field, val in fields:
  174. if isinstance(val, basestring) or not hasattr(val, "__iter__"):
  175. val = [val]
  176. for v in val:
  177. if v is not None:
  178. # Don't call str() on bytestrings: in Py3 it all goes wrong.
  179. if not isinstance(v, bytes):
  180. v = str(v)
  181. new_fields.append(
  182. (
  183. field.decode("utf-8")
  184. if isinstance(field, bytes)
  185. else field,
  186. v.encode("utf-8") if isinstance(v, str) else v,
  187. )
  188. )
  189. for k, v in files:
  190. # support for explicit filename
  191. ft = None
  192. fh = None
  193. if isinstance(v, (tuple, list)):
  194. if len(v) == 2:
  195. fn, fp = v
  196. elif len(v) == 3:
  197. fn, fp, ft = v
  198. else:
  199. fn, fp, ft, fh = v
  200. else:
  201. fn = guess_filename(v) or k
  202. fp = v
  203. if isinstance(fp, (str, bytes, bytearray)):
  204. fdata = fp
  205. elif isinstance(fp, _SupportsRead): # type: ignore[reportUnnecessaryIsInstance] # defensive check for untyped callers
  206. fdata = fp.read()
  207. elif fp is None: # type: ignore[reportUnnecessaryComparison] # defensive check for untyped callers
  208. continue
  209. else:
  210. fdata = fp
  211. rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
  212. rf.make_multipart(content_type=ft)
  213. new_fields.append(rf)
  214. body, content_type = encode_multipart_formdata(new_fields)
  215. return body, content_type
  216. class RequestHooksMixin:
  217. hooks: dict[str, list[_t.HookType]]
  218. def register_hook(
  219. self, event: str, hook: Iterable[_t.HookType] | _t.HookType
  220. ) -> None:
  221. """Properly register a hook."""
  222. if event not in self.hooks:
  223. raise ValueError(f'Unsupported event specified, with event name "{event}"')
  224. if isinstance(hook, Callable):
  225. self.hooks[event].append(hook)
  226. elif hasattr(hook, "__iter__"):
  227. self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) # type: ignore[reportUnnecessaryIsInstance] # defensive runtime filter
  228. def deregister_hook(self, event: str, hook: _t.HookType) -> bool:
  229. """Deregister a previously registered hook.
  230. Returns True if the hook existed, False if not.
  231. """
  232. try:
  233. self.hooks[event].remove(hook)
  234. return True
  235. except ValueError:
  236. return False
  237. class Request(RequestHooksMixin):
  238. """A user-created :class:`Request <Request>` object.
  239. Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
  240. :param method: HTTP method to use.
  241. :param url: URL to send.
  242. :param headers: dictionary of headers to send.
  243. :param files: dictionary of {filename: fileobject} files to multipart upload.
  244. :param data: the body to attach to the request. If a dictionary or
  245. list of tuples ``[(key, value)]`` is provided, form-encoding will
  246. take place.
  247. :param json: json for the body to attach to the request (if files or data is not specified).
  248. :param params: URL parameters to append to the URL. If a dictionary or
  249. list of tuples ``[(key, value)]`` is provided, form-encoding will
  250. take place.
  251. :param auth: Auth handler or (user, pass) tuple.
  252. :param cookies: dictionary or CookieJar of cookies to attach to this request.
  253. :param hooks: dictionary of callback hooks, for internal usage.
  254. Usage::
  255. >>> import requests
  256. >>> req = requests.Request('GET', 'https://httpbin.org/get')
  257. >>> req.prepare()
  258. <PreparedRequest [GET]>
  259. """
  260. method: str | None
  261. url: _t.UriType | None
  262. headers: Mapping[str, str | bytes]
  263. files: _t.FilesType
  264. data: _t.DataType
  265. json: _t.JsonType
  266. params: _t.ParamsType
  267. auth: _t.AuthType
  268. cookies: RequestsCookieJar | CookieJar | dict[str, str] | None
  269. def __init__(
  270. self,
  271. method: str | None = None,
  272. url: _t.UriType | None = None,
  273. headers: _t.HeadersType = None,
  274. files: _t.FilesType = None,
  275. data: _t.DataType = None,
  276. params: _t.ParamsType = None,
  277. auth: _t.AuthType = None,
  278. cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,
  279. hooks: _t.HooksInputType | None = None,
  280. json: _t.JsonType = None,
  281. ) -> None:
  282. # Default empty dicts for dict params.
  283. data = [] if data is None else data
  284. files = [] if files is None else files
  285. headers = {} if headers is None else headers
  286. params = {} if params is None else params
  287. hooks = {} if hooks is None else hooks
  288. self.hooks = default_hooks()
  289. for k, v in list(hooks.items()):
  290. self.register_hook(event=k, hook=v)
  291. self.method = method
  292. self.url = url
  293. self.headers = headers
  294. self.files = files
  295. self.data = data
  296. self.json = json
  297. self.params = params
  298. self.auth = auth
  299. self.cookies = cookies
  300. def __repr__(self) -> str:
  301. return f"<Request [{self.method}]>"
  302. def prepare(self) -> PreparedRequest:
  303. """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
  304. p = PreparedRequest()
  305. p.prepare(
  306. method=self.method,
  307. url=self.url,
  308. headers=self.headers,
  309. files=self.files,
  310. data=self.data,
  311. json=self.json,
  312. params=self.params,
  313. auth=self.auth,
  314. cookies=self.cookies,
  315. hooks=self.hooks,
  316. )
  317. return p
  318. class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
  319. """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
  320. containing the exact bytes that will be sent to the server.
  321. Instances are generated from a :class:`Request <Request>` object, and
  322. should not be instantiated manually; doing so may produce undesirable
  323. effects.
  324. Usage::
  325. >>> import requests
  326. >>> req = requests.Request('GET', 'https://httpbin.org/get')
  327. >>> r = req.prepare()
  328. >>> r
  329. <PreparedRequest [GET]>
  330. >>> s = requests.Session()
  331. >>> s.send(r)
  332. <Response [200]>
  333. """
  334. method: str | None
  335. url: str | None
  336. headers: CaseInsensitiveDict[str | bytes]
  337. _cookies: RequestsCookieJar | CookieJar | None
  338. body: _t.BodyType
  339. hooks: dict[str, list[_t.HookType]]
  340. _body_position: int | object | None
  341. def __init__(self) -> None:
  342. #: HTTP verb to send to the server.
  343. self.method = None
  344. #: HTTP URL to send the request to.
  345. self.url = None
  346. #: dictionary of HTTP headers.
  347. self.headers = None # type: ignore[assignment]
  348. # The `CookieJar` used to create the Cookie header will be stored here
  349. # after prepare_cookies is called
  350. self._cookies = None
  351. #: request body to send to the server.
  352. self.body = None
  353. #: dictionary of callback hooks, for internal usage.
  354. self.hooks = default_hooks()
  355. #: integer denoting starting position of a readable file-like body.
  356. self._body_position = None
  357. def prepare(
  358. self,
  359. method: str | None = None,
  360. url: _t.UriType | None = None,
  361. headers: Mapping[str, str | bytes] | None = None,
  362. files: _t.FilesType = None,
  363. data: _t.DataType = None,
  364. params: _t.ParamsType = None,
  365. auth: _t.AuthType = None,
  366. cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,
  367. hooks: _t.HooksInputType | None = None,
  368. json: _t.JsonType = None,
  369. ) -> None:
  370. """Prepares the entire request with the given parameters."""
  371. url = cast("_t.UriType", url)
  372. self.prepare_method(method)
  373. self.prepare_url(url, params)
  374. self.prepare_headers(headers)
  375. self.prepare_cookies(cookies)
  376. self.prepare_body(data, files, json)
  377. self.prepare_auth(auth, url)
  378. # Note that prepare_auth must be last to enable authentication schemes
  379. # such as OAuth to work on a fully prepared request.
  380. # This MUST go after prepare_auth. Authenticators could add a hook
  381. self.prepare_hooks(hooks)
  382. def __repr__(self) -> str:
  383. return f"<PreparedRequest [{self.method}]>"
  384. def copy(self) -> PreparedRequest:
  385. p = PreparedRequest()
  386. p.method = self.method
  387. p.url = self.url
  388. p.headers = self.headers.copy() if self.headers is not None else None # type: ignore[assignment]
  389. p._cookies = _copy_cookie_jar(self._cookies)
  390. p.body = self.body
  391. p.hooks = self.hooks
  392. p._body_position = self._body_position
  393. return p
  394. def prepare_method(self, method: str | None) -> None:
  395. """Prepares the given HTTP method."""
  396. self.method = method
  397. if self.method is not None:
  398. self.method = to_native_string(self.method.upper())
  399. @staticmethod
  400. def _get_idna_encoded_host(host: str) -> str:
  401. import idna
  402. try:
  403. host = idna.encode(host, uts46=True).decode("utf-8")
  404. except idna.IDNAError:
  405. raise UnicodeError
  406. return host
  407. def prepare_url(
  408. self,
  409. url: _t.UriType,
  410. params: _t.ParamsType,
  411. ) -> None:
  412. """Prepares the given HTTP URL."""
  413. #: Accept objects that have string representations.
  414. #: We're unable to blindly call unicode/str functions
  415. #: as this will include the bytestring indicator (b'')
  416. #: on python 3.x.
  417. #: https://github.com/psf/requests/pull/2238
  418. if isinstance(url, bytes):
  419. url = url.decode("utf8")
  420. else:
  421. url = str(url)
  422. # Remove leading whitespaces from url
  423. url = url.lstrip()
  424. # Don't do any URL preparation for non-HTTP schemes like `mailto`,
  425. # `data` etc to work around exceptions from `url_parse`, which
  426. # handles RFC 3986 only.
  427. if ":" in url and not url.lower().startswith("http"):
  428. self.url = url
  429. return
  430. # Support for unicode domain names and paths.
  431. try:
  432. scheme, auth, host, port, path, query, fragment = parse_url(url)
  433. except LocationParseError as e:
  434. raise InvalidURL(*e.args)
  435. if not scheme:
  436. raise MissingSchema(
  437. f"Invalid URL {url!r}: No scheme supplied. "
  438. f"Perhaps you meant https://{url}?"
  439. )
  440. if not host:
  441. raise InvalidURL(f"Invalid URL {url!r}: No host supplied")
  442. # In general, we want to try IDNA encoding the hostname if the string contains
  443. # non-ASCII characters. This allows users to automatically get the correct IDNA
  444. # behaviour. For strings containing only ASCII characters, we need to also verify
  445. # it doesn't start with a wildcard (*), before allowing the unencoded hostname.
  446. if not unicode_is_ascii(host):
  447. try:
  448. host = self._get_idna_encoded_host(host)
  449. except UnicodeError:
  450. raise InvalidURL("URL has an invalid label.")
  451. elif host.startswith(("*", ".")):
  452. raise InvalidURL("URL has an invalid label.")
  453. # Carefully reconstruct the network location
  454. netloc = auth or ""
  455. if netloc:
  456. netloc += "@"
  457. netloc += host
  458. if port:
  459. netloc += f":{port}"
  460. # Bare domains aren't valid URLs.
  461. if not path:
  462. path = "/"
  463. if isinstance(params, (str, bytes)):
  464. params = to_native_string(params)
  465. if params is not None:
  466. enc_params = self._encode_params(params)
  467. else:
  468. enc_params = ""
  469. if enc_params:
  470. if query:
  471. query = f"{query}&{enc_params}"
  472. else:
  473. query = enc_params
  474. url = requote_uri(urlunparse((scheme, netloc, path, "", query, fragment)))
  475. self.url = url
  476. def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None:
  477. """Prepares the given HTTP headers."""
  478. self.headers = CaseInsensitiveDict()
  479. if headers:
  480. for header in headers.items():
  481. # Raise exception on invalid header value.
  482. check_header_validity(header)
  483. name, value = header
  484. self.headers[to_native_string(name)] = value
  485. def prepare_body(
  486. self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None
  487. ) -> None:
  488. """Prepares the given HTTP body data."""
  489. # Check if file, fo, generator, iterator.
  490. # If not, run through normal process.
  491. # Nottin' on you.
  492. body = None
  493. content_type = None
  494. if not data and json is not None:
  495. # urllib3 requires a bytes-like body. Python 2's json.dumps
  496. # provides this natively, but Python 3 gives a Unicode string.
  497. content_type = "application/json"
  498. try:
  499. body = complexjson.dumps(json, allow_nan=False)
  500. except ValueError as ve:
  501. raise InvalidJSONError(ve, request=self)
  502. if not isinstance(body, bytes):
  503. body = body.encode("utf-8")
  504. # data that proxies attributes to underlying objects needs hasattr
  505. is_iterable = isinstance(data, Iterable) or hasattr(data, "__iter__")
  506. if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)):
  507. try:
  508. length = super_len(data)
  509. except (TypeError, AttributeError, UnsupportedOperation):
  510. length = None
  511. body = data
  512. if getattr(body, "tell", None) is not None:
  513. # Record the current file position before reading.
  514. # This will allow us to rewind a file in the event
  515. # of a redirect.
  516. try:
  517. self._body_position = body.tell() # type: ignore[union-attr] # guarded by getattr check
  518. except OSError:
  519. # This differentiates from None, allowing us to catch
  520. # a failed `tell()` later when trying to rewind the body
  521. self._body_position = object()
  522. if files:
  523. raise NotImplementedError(
  524. "Streamed bodies and files are mutually exclusive."
  525. )
  526. if length:
  527. self.headers["Content-Length"] = builtin_str(length)
  528. else:
  529. self.headers["Transfer-Encoding"] = "chunked"
  530. else:
  531. # After is_stream filtering, remaining data is raw (not streamed)
  532. raw_data = cast("_t.RawDataType | None", data)
  533. # Multi-part file uploads.
  534. if files:
  535. (body, content_type) = self._encode_files(files, raw_data)
  536. else:
  537. if raw_data:
  538. body = self._encode_params(raw_data)
  539. if isinstance(data, basestring) or isinstance(data, _SupportsRead):
  540. content_type = None
  541. else:
  542. content_type = "application/x-www-form-urlencoded"
  543. self.prepare_content_length(body)
  544. # Add content-type if it wasn't explicitly provided.
  545. if content_type and ("content-type" not in self.headers):
  546. self.headers["Content-Type"] = content_type
  547. self.body = body # type: ignore[assignment] # body transforms from DataType to BodyType
  548. def prepare_content_length(self, body: _t.BodyType) -> None:
  549. """Prepare Content-Length header based on request method and body"""
  550. if body is not None:
  551. length = super_len(body)
  552. if length:
  553. # If length exists, set it. Otherwise, we fallback
  554. # to Transfer-Encoding: chunked.
  555. self.headers["Content-Length"] = builtin_str(length)
  556. elif (
  557. self.method not in ("GET", "HEAD")
  558. and self.headers.get("Content-Length") is None
  559. ):
  560. # Set Content-Length to 0 for methods that can have a body
  561. # but don't provide one. (i.e. not GET or HEAD)
  562. self.headers["Content-Length"] = "0"
  563. def prepare_auth(
  564. self,
  565. auth: _t.AuthType,
  566. url: _t.UriType = "",
  567. ) -> None:
  568. """Prepares the given HTTP auth data."""
  569. # If no Auth is explicitly provided, extract it from the URL first.
  570. if auth is None:
  571. url_auth = get_auth_from_url(cast(str, self.url))
  572. auth = url_auth if any(url_auth) else None
  573. if auth:
  574. if isinstance(auth, tuple) and len(auth) == 2: # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType
  575. # special-case basic HTTP auth
  576. auth_handler = HTTPBasicAuth(*auth) # type: ignore[arg-type] # pyright widens tuple from Callable in AuthType
  577. else:
  578. # TODO: can be fixed by flipping the conditionals
  579. auth_handler = cast("Callable[..., PreparedRequest]", auth)
  580. # Allow auth to make its changes.
  581. r = auth_handler(self)
  582. # Update self to reflect the auth changes.
  583. self.__dict__.update(r.__dict__)
  584. # Recompute Content-Length
  585. self.prepare_content_length(self.body)
  586. def prepare_cookies(
  587. self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None
  588. ) -> None:
  589. """Prepares the given HTTP cookie data.
  590. This function eventually generates a ``Cookie`` header from the
  591. given cookies using cookielib. Due to cookielib's design, the header
  592. will not be regenerated if it already exists, meaning this function
  593. can only be called once for the life of the
  594. :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
  595. to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
  596. header is removed beforehand.
  597. """
  598. if isinstance(cookies, cookielib.CookieJar):
  599. self._cookies = cookies
  600. else:
  601. self._cookies = cookiejar_from_dict(cookies)
  602. cookies_jar = cast("CookieJar", self._cookies)
  603. cookie_header = get_cookie_header(cookies_jar, self)
  604. if cookie_header is not None:
  605. self.headers["Cookie"] = cookie_header
  606. def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None:
  607. """Prepares the given hooks."""
  608. # hooks can be passed as None to the prepare method and to this
  609. # method. To prevent iterating over None, simply use an empty list
  610. # if hooks is False-y
  611. hooks = hooks or {}
  612. for event in hooks:
  613. self.register_hook(event, hooks[event])
  614. class Response:
  615. """The :class:`Response <Response>` object, which contains a
  616. server's response to an HTTP request.
  617. """
  618. _content: bytes | Literal[False] | None
  619. _content_consumed: bool
  620. _next: PreparedRequest | None
  621. status_code: int
  622. headers: CaseInsensitiveDict[str]
  623. raw: Any
  624. url: str
  625. encoding: str | None
  626. history: list[Response]
  627. reason: str
  628. cookies: RequestsCookieJar
  629. elapsed: datetime.timedelta
  630. request: PreparedRequest
  631. connection: HTTPAdapter
  632. __attrs__: list[str] = [
  633. "_content",
  634. "status_code",
  635. "headers",
  636. "url",
  637. "history",
  638. "encoding",
  639. "reason",
  640. "cookies",
  641. "elapsed",
  642. "request",
  643. ]
  644. def __init__(self) -> None:
  645. self._content = False
  646. self._content_consumed = False
  647. self._next = None
  648. #: Integer Code of responded HTTP Status, e.g. 404 or 200.
  649. self.status_code = None # type: ignore[assignment]
  650. #: Case-insensitive Dictionary of Response Headers.
  651. #: For example, ``headers['content-encoding']`` will return the
  652. #: value of a ``'Content-Encoding'`` response header.
  653. self.headers = CaseInsensitiveDict()
  654. #: File-like object representation of response (for advanced usage).
  655. #: Use of ``raw`` requires that ``stream=True`` be set on the request.
  656. #: This requirement does not apply for use internally to Requests.
  657. self.raw = None
  658. #: Final URL location of Response.
  659. self.url = None # type: ignore[assignment]
  660. #: Encoding to decode with when accessing r.text.
  661. self.encoding = None
  662. #: A list of :class:`Response <Response>` objects from
  663. #: the history of the Request. Any redirect responses will end
  664. #: up here. The list is sorted from the oldest to the most recent request.
  665. self.history = []
  666. #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
  667. self.reason = None # type: ignore[assignment]
  668. #: A CookieJar of Cookies the server sent back.
  669. self.cookies = cookiejar_from_dict({})
  670. #: The amount of time elapsed between sending the request
  671. #: and the arrival of the response (as a timedelta).
  672. #: This property specifically measures the time taken between sending
  673. #: the first byte of the request and finishing parsing the headers. It
  674. #: is therefore unaffected by consuming the response content or the
  675. #: value of the ``stream`` keyword argument.
  676. self.elapsed = datetime.timedelta(0)
  677. #: The :class:`PreparedRequest <PreparedRequest>` object to which this
  678. #: is a response.
  679. self.request = None # type: ignore[assignment]
  680. def __enter__(self) -> Self:
  681. return self
  682. def __exit__(self, *args: Any) -> None:
  683. self.close()
  684. def __getstate__(self) -> dict[str, Any]:
  685. # Consume everything; accessing the content attribute makes
  686. # sure the content has been fully read.
  687. if not self._content_consumed:
  688. self.content
  689. return {attr: getattr(self, attr, None) for attr in self.__attrs__}
  690. def __setstate__(self, state: dict[str, Any]) -> None:
  691. for name, value in state.items():
  692. setattr(self, name, value)
  693. # pickled objects do not have .raw
  694. setattr(self, "_content_consumed", True)
  695. setattr(self, "raw", None)
  696. def __repr__(self) -> str:
  697. return f"<Response [{self.status_code}]>"
  698. def __bool__(self) -> bool:
  699. """Returns True if :attr:`status_code` is less than 400.
  700. This attribute checks if the status code of the response is between
  701. 400 and 600 to see if there was a client error or a server error. If
  702. the status code, is between 200 and 400, this will return True. This
  703. is **not** a check to see if the response code is ``200 OK``.
  704. """
  705. return self.ok
  706. def __nonzero__(self) -> bool:
  707. """Returns True if :attr:`status_code` is less than 400.
  708. This attribute checks if the status code of the response is between
  709. 400 and 600 to see if there was a client error or a server error. If
  710. the status code, is between 200 and 400, this will return True. This
  711. is **not** a check to see if the response code is ``200 OK``.
  712. """
  713. return self.ok
  714. def __iter__(self) -> Iterator[bytes]:
  715. """Allows you to use a response as an iterator."""
  716. return self.iter_content(128)
  717. @property
  718. def ok(self) -> bool:
  719. """Returns True if :attr:`status_code` is less than 400, False if not.
  720. This attribute checks if the status code of the response is between
  721. 400 and 600 to see if there was a client error or a server error. If
  722. the status code is between 200 and 400, this will return True. This
  723. is **not** a check to see if the response code is ``200 OK``.
  724. """
  725. try:
  726. self.raise_for_status()
  727. except HTTPError:
  728. return False
  729. return True
  730. @property
  731. def is_redirect(self) -> bool:
  732. """True if this Response is a well-formed HTTP redirect that could have
  733. been processed automatically (by :meth:`Session.resolve_redirects`).
  734. """
  735. return "location" in self.headers and self.status_code in REDIRECT_STATI
  736. @property
  737. def is_permanent_redirect(self) -> bool:
  738. """True if this Response one of the permanent versions of redirect."""
  739. return "location" in self.headers and self.status_code in (
  740. codes.moved_permanently,
  741. codes.permanent_redirect,
  742. )
  743. @property
  744. def next(self) -> PreparedRequest | None:
  745. """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
  746. return self._next
  747. @property
  748. def apparent_encoding(self) -> str | None:
  749. """The apparent encoding, provided by the charset_normalizer or chardet libraries."""
  750. if chardet is not None:
  751. return chardet.detect(self.content)["encoding"]
  752. else:
  753. # If no character detection library is available, we'll fall back
  754. # to a standard Python utf-8 str.
  755. return "utf-8"
  756. @overload
  757. def iter_content(
  758. self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False
  759. ) -> Iterator[bytes]: ...
  760. @overload
  761. def iter_content(
  762. self, chunk_size: int | None = 1, *, decode_unicode: Literal[True]
  763. ) -> Iterator[str | bytes]: ...
  764. def iter_content(
  765. self, chunk_size: int | None = 1, decode_unicode: bool = False
  766. ) -> Iterator[str | bytes]:
  767. """Iterates over the response data. When stream=True is set on the
  768. request, this avoids reading the content at once into memory for
  769. large responses. The chunk size is the number of bytes it should
  770. read into memory. This is not necessarily the length of each item
  771. returned as decoding can take place.
  772. chunk_size must be of type int or None. A value of None will
  773. function differently depending on the value of `stream`.
  774. stream=True will read data as it arrives in whatever size the
  775. chunks are received. If stream=False, data is returned as
  776. a single chunk.
  777. If decode_unicode is True, content will be decoded using encoding
  778. information from the response. If no encoding information is available,
  779. bytes will be returned. This can be bypassed by manually setting
  780. `encoding` on the response.
  781. """
  782. def generate() -> Generator[bytes, None, None]:
  783. # Special case for urllib3.
  784. if hasattr(self.raw, "stream"):
  785. try:
  786. yield from self.raw.stream(chunk_size, decode_content=True)
  787. except ProtocolError as e:
  788. raise ChunkedEncodingError(e)
  789. except DecodeError as e:
  790. raise ContentDecodingError(e)
  791. except ReadTimeoutError as e:
  792. raise ConnectionError(e)
  793. except SSLError as e:
  794. raise RequestsSSLError(e)
  795. else:
  796. # Standard file-like object.
  797. while True:
  798. chunk = self.raw.read(chunk_size)
  799. if not chunk:
  800. break
  801. yield chunk
  802. self._content_consumed = True
  803. if self._content_consumed and isinstance(self._content, bool):
  804. raise StreamConsumedError()
  805. elif chunk_size is not None and not isinstance(chunk_size, int): # type: ignore[reportUnnecessaryIsInstance] # runtime guard for untyped callers
  806. raise TypeError(
  807. f"chunk_size must be an int, it is instead a {type(chunk_size)}."
  808. )
  809. if self._content_consumed:
  810. # simulate reading small chunks of the content
  811. content = cast(bytes, self._content)
  812. chunks = iter_slices(content, chunk_size)
  813. else:
  814. chunks = generate()
  815. if decode_unicode:
  816. chunks = stream_decode_response_unicode(chunks, self)
  817. return chunks
  818. @overload
  819. def iter_lines(
  820. self,
  821. chunk_size: int = ITER_CHUNK_SIZE,
  822. decode_unicode: Literal[False] = False,
  823. delimiter: bytes | None = None,
  824. ) -> Iterator[bytes]: ...
  825. @overload
  826. def iter_lines(
  827. self,
  828. chunk_size: int = ITER_CHUNK_SIZE,
  829. *,
  830. decode_unicode: Literal[True],
  831. delimiter: str | bytes | None = None,
  832. ) -> Iterator[str | bytes]: ...
  833. def iter_lines(
  834. self,
  835. chunk_size: int = ITER_CHUNK_SIZE,
  836. decode_unicode: bool = False,
  837. delimiter: str | bytes | None = None,
  838. ) -> Iterator[str | bytes]:
  839. """Iterates over the response data, one line at a time. When
  840. stream=True is set on the request, this avoids reading the
  841. content at once into memory for large responses.
  842. The decode_unicode param works the same as in `iter_content`, with the
  843. same caveats.
  844. .. note:: This method is not reentrant safe.
  845. """
  846. pending: str | bytes | None = None
  847. for chunk in self.iter_content(
  848. chunk_size=chunk_size, decode_unicode=decode_unicode
  849. ):
  850. if pending is not None:
  851. # TODO: remove cast after iter_lines rewrite
  852. chunk = cast("str | bytes", pending + chunk) # type: ignore[operator]
  853. if delimiter:
  854. lines = chunk.split(delimiter) # type: ignore[arg-type]
  855. else:
  856. lines = chunk.splitlines()
  857. if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
  858. pending = lines.pop()
  859. else:
  860. pending = None
  861. yield from lines
  862. if pending is not None:
  863. yield pending
  864. @property
  865. def content(self) -> bytes:
  866. """Content of the response, in bytes."""
  867. if self._content is False:
  868. # Read the contents.
  869. if self._content_consumed:
  870. raise RuntimeError("The content for this response was already consumed")
  871. if self.status_code == 0 or self.raw is None:
  872. self._content = None
  873. else:
  874. self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""
  875. self._content_consumed = True
  876. # don't need to release the connection; that's been handled by urllib3
  877. # since we exhausted the data.
  878. return self._content # type: ignore[return-value]
  879. @property
  880. def text(self) -> str:
  881. """Content of the response, in unicode.
  882. If Response.encoding is None, encoding will be guessed using
  883. ``charset_normalizer`` or ``chardet``.
  884. The encoding of the response content is determined based solely on HTTP
  885. headers, following RFC 2616 to the letter. If you can take advantage of
  886. non-HTTP knowledge to make a better guess at the encoding, you should
  887. set ``r.encoding`` appropriately before accessing this property.
  888. """
  889. # Try charset from content-type
  890. content = None
  891. encoding = self.encoding
  892. if not self.content:
  893. return ""
  894. # Fallback to auto-detected encoding.
  895. if self.encoding is None:
  896. encoding = self.apparent_encoding
  897. # Decode unicode from given encoding.
  898. try:
  899. content = str(self.content, encoding or "utf-8", errors="replace")
  900. except (LookupError, TypeError):
  901. # A LookupError is raised if the encoding was not found which could
  902. # indicate a misspelling or similar mistake.
  903. #
  904. # A TypeError can be raised if encoding is None
  905. #
  906. # So we try blindly encoding.
  907. content = str(self.content, errors="replace")
  908. return content
  909. def json(self, **kwargs: Any) -> Any:
  910. r"""Decodes the JSON response body (if any) as a Python object.
  911. This may return a dictionary, list, etc. depending on what is in the response.
  912. :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
  913. :raises requests.exceptions.JSONDecodeError: If the response body does not
  914. contain valid json.
  915. """
  916. if not self.encoding and self.content and len(self.content) > 3:
  917. # No encoding set. JSON RFC 4627 section 3 states we should expect
  918. # UTF-8, -16 or -32. Detect which one to use; If the detection or
  919. # decoding fails, fall back to `self.text` (using charset_normalizer to make
  920. # a best guess).
  921. encoding = guess_json_utf(self.content)
  922. if encoding is not None:
  923. try:
  924. return complexjson.loads(self.content.decode(encoding), **kwargs)
  925. except UnicodeDecodeError:
  926. # Wrong UTF codec detected; usually because it's not UTF-8
  927. # but some other 8-bit codec. This is an RFC violation,
  928. # and the server didn't bother to tell us what codec *was*
  929. # used.
  930. pass
  931. except JSONDecodeError as e:
  932. raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
  933. try:
  934. return complexjson.loads(self.text, **kwargs)
  935. except JSONDecodeError as e:
  936. # Catch JSON-related errors and raise as requests.JSONDecodeError
  937. # This aliases json.JSONDecodeError and simplejson.JSONDecodeError
  938. raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
  939. @property
  940. def links(self) -> dict[str, dict[str, str]]:
  941. """Returns the parsed header links of the response, if any."""
  942. header = self.headers.get("link")
  943. resolved_links: dict[str, dict[str, str]] = {}
  944. if header:
  945. links = parse_header_links(header)
  946. for link in links:
  947. key = link.get("rel") or link.get("url")
  948. if key is not None:
  949. resolved_links[key] = link
  950. return resolved_links
  951. def raise_for_status(self) -> None:
  952. """Raises :class:`HTTPError`, if one occurred."""
  953. http_error_msg = ""
  954. if isinstance(self.reason, bytes):
  955. # We attempt to decode utf-8 first because some servers
  956. # choose to localize their reason strings. If the string
  957. # isn't utf-8, we fall back to iso-8859-1 for all other
  958. # encodings. (See PR #3538)
  959. try:
  960. reason = self.reason.decode("utf-8")
  961. except UnicodeDecodeError:
  962. reason = self.reason.decode("iso-8859-1")
  963. else:
  964. reason = self.reason
  965. if 400 <= self.status_code < 500:
  966. http_error_msg = (
  967. f"{self.status_code} Client Error: {reason} for url: {self.url}"
  968. )
  969. elif 500 <= self.status_code < 600:
  970. http_error_msg = (
  971. f"{self.status_code} Server Error: {reason} for url: {self.url}"
  972. )
  973. if http_error_msg:
  974. raise HTTPError(http_error_msg, response=self)
  975. def close(self) -> None:
  976. """Releases the connection back to the pool. Once this method has been
  977. called the underlying ``raw`` object must not be accessed again.
  978. *Note: Should not normally need to be called explicitly.*
  979. """
  980. if not self._content_consumed:
  981. self.raw.close()
  982. release_conn = getattr(self.raw, "release_conn", None)
  983. if release_conn is not None:
  984. release_conn()