models.py 33 KB

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