Plex plugin to to play various online streams (mostly Latvian).

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