Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 33KB

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