models.py 34 KB

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