models.py 34 KB

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