models.py 34 KB

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