models.py 29 KB

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