models.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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, 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 = _copy_cookie_jar(self._cookies)
  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(
  297. to_native_string(url, 'utf8')))
  298. if not host:
  299. raise InvalidURL("Invalid URL %r: No host supplied" % url)
  300. # Only want to apply IDNA to the hostname
  301. try:
  302. host = host.encode('idna').decode('utf-8')
  303. except UnicodeError:
  304. raise InvalidURL('URL has an invalid label.')
  305. # Carefully reconstruct the network location
  306. netloc = auth or ''
  307. if netloc:
  308. netloc += '@'
  309. netloc += host
  310. if port:
  311. netloc += ':' + str(port)
  312. # Bare domains aren't valid URLs.
  313. if not path:
  314. path = '/'
  315. if is_py2:
  316. if isinstance(scheme, str):
  317. scheme = scheme.encode('utf-8')
  318. if isinstance(netloc, str):
  319. netloc = netloc.encode('utf-8')
  320. if isinstance(path, str):
  321. path = path.encode('utf-8')
  322. if isinstance(query, str):
  323. query = query.encode('utf-8')
  324. if isinstance(fragment, str):
  325. fragment = fragment.encode('utf-8')
  326. enc_params = self._encode_params(params)
  327. if enc_params:
  328. if query:
  329. query = '%s&%s' % (query, enc_params)
  330. else:
  331. query = enc_params
  332. url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
  333. self.url = url
  334. def prepare_headers(self, headers):
  335. """Prepares the given HTTP headers."""
  336. if headers:
  337. self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())
  338. else:
  339. self.headers = CaseInsensitiveDict()
  340. def prepare_body(self, data, files, json=None):
  341. """Prepares the given HTTP body data."""
  342. # Check if file, fo, generator, iterator.
  343. # If not, run through normal process.
  344. # Nottin' on you.
  345. body = None
  346. content_type = None
  347. length = None
  348. if json is not None:
  349. content_type = 'application/json'
  350. body = json_dumps(json)
  351. is_stream = all([
  352. hasattr(data, '__iter__'),
  353. not isinstance(data, (basestring, list, tuple, dict))
  354. ])
  355. try:
  356. length = super_len(data)
  357. except (TypeError, AttributeError, UnsupportedOperation):
  358. length = None
  359. if is_stream:
  360. body = data
  361. if files:
  362. raise NotImplementedError('Streamed bodies and files are mutually exclusive.')
  363. if length is not None:
  364. self.headers['Content-Length'] = builtin_str(length)
  365. else:
  366. self.headers['Transfer-Encoding'] = 'chunked'
  367. else:
  368. # Multi-part file uploads.
  369. if files:
  370. (body, content_type) = self._encode_files(files, data)
  371. else:
  372. if data and json is None:
  373. body = self._encode_params(data)
  374. if isinstance(data, basestring) or hasattr(data, 'read'):
  375. content_type = None
  376. else:
  377. content_type = 'application/x-www-form-urlencoded'
  378. self.prepare_content_length(body)
  379. # Add content-type if it wasn't explicitly provided.
  380. if content_type and ('content-type' not in self.headers):
  381. self.headers['Content-Type'] = content_type
  382. self.body = body
  383. def prepare_content_length(self, body):
  384. if hasattr(body, 'seek') and hasattr(body, 'tell'):
  385. body.seek(0, 2)
  386. self.headers['Content-Length'] = builtin_str(body.tell())
  387. body.seek(0, 0)
  388. elif body is not None:
  389. l = super_len(body)
  390. if l:
  391. self.headers['Content-Length'] = builtin_str(l)
  392. elif (self.method not in ('GET', 'HEAD')) and (self.headers.get('Content-Length') is None):
  393. self.headers['Content-Length'] = '0'
  394. def prepare_auth(self, auth, url=''):
  395. """Prepares the given HTTP auth data."""
  396. # If no Auth is explicitly provided, extract it from the URL first.
  397. if auth is None:
  398. url_auth = get_auth_from_url(self.url)
  399. auth = url_auth if any(url_auth) else None
  400. if auth:
  401. if isinstance(auth, tuple) and len(auth) == 2:
  402. # special-case basic HTTP auth
  403. auth = HTTPBasicAuth(*auth)
  404. # Allow auth to make its changes.
  405. r = auth(self)
  406. # Update self to reflect the auth changes.
  407. self.__dict__.update(r.__dict__)
  408. # Recompute Content-Length
  409. self.prepare_content_length(self.body)
  410. def prepare_cookies(self, cookies):
  411. """Prepares the given HTTP cookie data.
  412. This function eventually generates a ``Cookie`` header from the
  413. given cookies using cookielib. Due to cookielib's design, the header
  414. will not be regenerated if it already exists, meaning this function
  415. can only be called once for the life of the
  416. :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
  417. to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
  418. header is removed beforehand."""
  419. if isinstance(cookies, cookielib.CookieJar):
  420. self._cookies = cookies
  421. else:
  422. self._cookies = cookiejar_from_dict(cookies)
  423. cookie_header = get_cookie_header(self._cookies, self)
  424. if cookie_header is not None:
  425. self.headers['Cookie'] = cookie_header
  426. def prepare_hooks(self, hooks):
  427. """Prepares the given hooks."""
  428. # hooks can be passed as None to the prepare method and to this
  429. # method. To prevent iterating over None, simply use an empty list
  430. # if hooks is False-y
  431. hooks = hooks or []
  432. for event in hooks:
  433. self.register_hook(event, hooks[event])
  434. class Response(object):
  435. """The :class:`Response <Response>` object, which contains a
  436. server's response to an HTTP request.
  437. """
  438. __attrs__ = [
  439. '_content',
  440. 'status_code',
  441. 'headers',
  442. 'url',
  443. 'history',
  444. 'encoding',
  445. 'reason',
  446. 'cookies',
  447. 'elapsed',
  448. 'request',
  449. ]
  450. def __init__(self):
  451. super(Response, self).__init__()
  452. self._content = False
  453. self._content_consumed = False
  454. #: Integer Code of responded HTTP Status, e.g. 404 or 200.
  455. self.status_code = None
  456. #: Case-insensitive Dictionary of Response Headers.
  457. #: For example, ``headers['content-encoding']`` will return the
  458. #: value of a ``'Content-Encoding'`` response header.
  459. self.headers = CaseInsensitiveDict()
  460. #: File-like object representation of response (for advanced usage).
  461. #: Use of ``raw`` requires that ``stream=True`` be set on the request.
  462. # This requirement does not apply for use internally to Requests.
  463. self.raw = None
  464. #: Final URL location of Response.
  465. self.url = None
  466. #: Encoding to decode with when accessing r.text.
  467. self.encoding = None
  468. #: A list of :class:`Response <Response>` objects from
  469. #: the history of the Request. Any redirect responses will end
  470. #: up here. The list is sorted from the oldest to the most recent request.
  471. self.history = []
  472. #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
  473. self.reason = None
  474. #: A CookieJar of Cookies the server sent back.
  475. self.cookies = cookiejar_from_dict({})
  476. #: The amount of time elapsed between sending the request
  477. #: and the arrival of the response (as a timedelta).
  478. #: This property specifically measures the time taken between sending
  479. #: the first byte of the request and finishing parsing the headers. It
  480. #: is therefore unaffected by consuming the response content or the
  481. #: value of the ``stream`` keyword argument.
  482. self.elapsed = datetime.timedelta(0)
  483. #: The :class:`PreparedRequest <PreparedRequest>` object to which this
  484. #: is a response.
  485. self.request = None
  486. def __getstate__(self):
  487. # Consume everything; accessing the content attribute makes
  488. # sure the content has been fully read.
  489. if not self._content_consumed:
  490. self.content
  491. return dict(
  492. (attr, getattr(self, attr, None))
  493. for attr in self.__attrs__
  494. )
  495. def __setstate__(self, state):
  496. for name, value in state.items():
  497. setattr(self, name, value)
  498. # pickled objects do not have .raw
  499. setattr(self, '_content_consumed', True)
  500. setattr(self, 'raw', None)
  501. def __repr__(self):
  502. return '<Response [%s]>' % (self.status_code)
  503. def __bool__(self):
  504. """Returns true if :attr:`status_code` is 'OK'."""
  505. return self.ok
  506. def __nonzero__(self):
  507. """Returns true if :attr:`status_code` is 'OK'."""
  508. return self.ok
  509. def __iter__(self):
  510. """Allows you to use a response as an iterator."""
  511. return self.iter_content(128)
  512. @property
  513. def ok(self):
  514. try:
  515. self.raise_for_status()
  516. except HTTPError:
  517. return False
  518. return True
  519. @property
  520. def is_redirect(self):
  521. """True if this Response is a well-formed HTTP redirect that could have
  522. been processed automatically (by :meth:`Session.resolve_redirects`).
  523. """
  524. return ('location' in self.headers and self.status_code in REDIRECT_STATI)
  525. @property
  526. def is_permanent_redirect(self):
  527. """True if this Response one of the permanant versions of redirect"""
  528. return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
  529. @property
  530. def apparent_encoding(self):
  531. """The apparent encoding, provided by the chardet library"""
  532. return chardet.detect(self.content)['encoding']
  533. def iter_content(self, chunk_size=1, decode_unicode=False):
  534. """Iterates over the response data. When stream=True is set on the
  535. request, this avoids reading the content at once into memory for
  536. large responses. The chunk size is the number of bytes it should
  537. read into memory. This is not necessarily the length of each item
  538. returned as decoding can take place.
  539. If decode_unicode is True, content will be decoded using the best
  540. available encoding based on the response.
  541. """
  542. def generate():
  543. try:
  544. # Special case for urllib3.
  545. try:
  546. for chunk in self.raw.stream(chunk_size, decode_content=True):
  547. yield chunk
  548. except ProtocolError as e:
  549. raise ChunkedEncodingError(e)
  550. except DecodeError as e:
  551. raise ContentDecodingError(e)
  552. except ReadTimeoutError as e:
  553. raise ConnectionError(e)
  554. except AttributeError:
  555. # Standard file-like object.
  556. while True:
  557. chunk = self.raw.read(chunk_size)
  558. if not chunk:
  559. break
  560. yield chunk
  561. self._content_consumed = True
  562. if self._content_consumed and isinstance(self._content, bool):
  563. raise StreamConsumedError()
  564. # simulate reading small chunks of the content
  565. reused_chunks = iter_slices(self._content, chunk_size)
  566. stream_chunks = generate()
  567. chunks = reused_chunks if self._content_consumed else stream_chunks
  568. if decode_unicode:
  569. chunks = stream_decode_response_unicode(chunks, self)
  570. return chunks
  571. def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None):
  572. """Iterates over the response data, one line at a time. When
  573. stream=True is set on the request, this avoids reading the
  574. content at once into memory for large responses.
  575. .. note:: This method is not reentrant safe.
  576. """
  577. pending = None
  578. for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
  579. if pending is not None:
  580. chunk = pending + chunk
  581. if delimiter:
  582. lines = chunk.split(delimiter)
  583. else:
  584. lines = chunk.splitlines()
  585. if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
  586. pending = lines.pop()
  587. else:
  588. pending = None
  589. for line in lines:
  590. yield line
  591. if pending is not None:
  592. yield pending
  593. @property
  594. def content(self):
  595. """Content of the response, in bytes."""
  596. if self._content is False:
  597. # Read the contents.
  598. try:
  599. if self._content_consumed:
  600. raise RuntimeError(
  601. 'The content for this response was already consumed')
  602. if self.status_code == 0:
  603. self._content = None
  604. else:
  605. self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
  606. except AttributeError:
  607. self._content = None
  608. self._content_consumed = True
  609. # don't need to release the connection; that's been handled by urllib3
  610. # since we exhausted the data.
  611. return self._content
  612. @property
  613. def text(self):
  614. """Content of the response, in unicode.
  615. If Response.encoding is None, encoding will be guessed using
  616. ``chardet``.
  617. The encoding of the response content is determined based solely on HTTP
  618. headers, following RFC 2616 to the letter. If you can take advantage of
  619. non-HTTP knowledge to make a better guess at the encoding, you should
  620. set ``r.encoding`` appropriately before accessing this property.
  621. """
  622. # Try charset from content-type
  623. content = None
  624. encoding = self.encoding
  625. if not self.content:
  626. return str('')
  627. # Fallback to auto-detected encoding.
  628. if self.encoding is None:
  629. encoding = self.apparent_encoding
  630. # Decode unicode from given encoding.
  631. try:
  632. content = str(self.content, encoding, errors='replace')
  633. except (LookupError, TypeError):
  634. # A LookupError is raised if the encoding was not found which could
  635. # indicate a misspelling or similar mistake.
  636. #
  637. # A TypeError can be raised if encoding is None
  638. #
  639. # So we try blindly encoding.
  640. content = str(self.content, errors='replace')
  641. return content
  642. def json(self, **kwargs):
  643. """Returns the json-encoded content of a response, if any.
  644. :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
  645. """
  646. if not self.encoding and len(self.content) > 3:
  647. # No encoding set. JSON RFC 4627 section 3 states we should expect
  648. # UTF-8, -16 or -32. Detect which one to use; If the detection or
  649. # decoding fails, fall back to `self.text` (using chardet to make
  650. # a best guess).
  651. encoding = guess_json_utf(self.content)
  652. if encoding is not None:
  653. try:
  654. return json.loads(self.content.decode(encoding), **kwargs)
  655. except UnicodeDecodeError:
  656. # Wrong UTF codec detected; usually because it's not UTF-8
  657. # but some other 8-bit codec. This is an RFC violation,
  658. # and the server didn't bother to tell us what codec *was*
  659. # used.
  660. pass
  661. return json.loads(self.text, **kwargs)
  662. @property
  663. def links(self):
  664. """Returns the parsed header links of the response, if any."""
  665. header = self.headers.get('link')
  666. # l = MultiDict()
  667. l = {}
  668. if header:
  669. links = parse_header_links(header)
  670. for link in links:
  671. key = link.get('rel') or link.get('url')
  672. l[key] = link
  673. return l
  674. def raise_for_status(self):
  675. """Raises stored :class:`HTTPError`, if one occurred."""
  676. http_error_msg = ''
  677. if 400 <= self.status_code < 500:
  678. http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)
  679. elif 500 <= self.status_code < 600:
  680. http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason)
  681. if http_error_msg:
  682. raise HTTPError(http_error_msg, response=self)
  683. def close(self):
  684. """Releases the connection back to the pool. Once this method has been
  685. called the underlying ``raw`` object must not be accessed again.
  686. *Note: Should not normally need to be called explicitly.*
  687. """
  688. return self.raw.release_conn()