models.py 28 KB

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