Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 34KB

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