models.py 35 KB

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