response.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. from __future__ import absolute_import
  2. import io
  3. import logging
  4. import sys
  5. import warnings
  6. import zlib
  7. from contextlib import contextmanager
  8. from socket import error as SocketError
  9. from socket import timeout as SocketTimeout
  10. brotli = None
  11. from . import util
  12. from ._collections import HTTPHeaderDict
  13. from .connection import BaseSSLError, HTTPException
  14. from .exceptions import (
  15. BodyNotHttplibCompatible,
  16. DecodeError,
  17. HTTPError,
  18. IncompleteRead,
  19. InvalidChunkLength,
  20. InvalidHeader,
  21. ProtocolError,
  22. ReadTimeoutError,
  23. ResponseNotChunked,
  24. SSLError,
  25. )
  26. from .packages import six
  27. from .util.response import is_fp_closed, is_response_to_head
  28. log = logging.getLogger(__name__)
  29. class DeflateDecoder(object):
  30. def __init__(self):
  31. self._first_try = True
  32. self._data = b""
  33. self._obj = zlib.decompressobj()
  34. def __getattr__(self, name):
  35. return getattr(self._obj, name)
  36. def decompress(self, data):
  37. if not data:
  38. return data
  39. if not self._first_try:
  40. return self._obj.decompress(data)
  41. self._data += data
  42. try:
  43. decompressed = self._obj.decompress(data)
  44. if decompressed:
  45. self._first_try = False
  46. self._data = None
  47. return decompressed
  48. except zlib.error:
  49. self._first_try = False
  50. self._obj = zlib.decompressobj(-zlib.MAX_WBITS)
  51. try:
  52. return self.decompress(self._data)
  53. finally:
  54. self._data = None
  55. class GzipDecoderState(object):
  56. FIRST_MEMBER = 0
  57. OTHER_MEMBERS = 1
  58. SWALLOW_DATA = 2
  59. class GzipDecoder(object):
  60. def __init__(self):
  61. self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
  62. self._state = GzipDecoderState.FIRST_MEMBER
  63. def __getattr__(self, name):
  64. return getattr(self._obj, name)
  65. def decompress(self, data):
  66. ret = bytearray()
  67. if self._state == GzipDecoderState.SWALLOW_DATA or not data:
  68. return bytes(ret)
  69. while True:
  70. try:
  71. ret += self._obj.decompress(data)
  72. except zlib.error:
  73. previous_state = self._state
  74. # Ignore data after the first error
  75. self._state = GzipDecoderState.SWALLOW_DATA
  76. if previous_state == GzipDecoderState.OTHER_MEMBERS:
  77. # Allow trailing garbage acceptable in other gzip clients
  78. return bytes(ret)
  79. raise
  80. data = self._obj.unused_data
  81. if not data:
  82. return bytes(ret)
  83. self._state = GzipDecoderState.OTHER_MEMBERS
  84. self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
  85. if brotli is not None:
  86. class BrotliDecoder(object):
  87. # Supports both 'brotlipy' and 'Brotli' packages
  88. # since they share an import name. The top branches
  89. # are for 'brotlipy' and bottom branches for 'Brotli'
  90. def __init__(self):
  91. self._obj = brotli.Decompressor()
  92. if hasattr(self._obj, "decompress"):
  93. self.decompress = self._obj.decompress
  94. else:
  95. self.decompress = self._obj.process
  96. def flush(self):
  97. if hasattr(self._obj, "flush"):
  98. return self._obj.flush()
  99. return b""
  100. class MultiDecoder(object):
  101. """
  102. From RFC7231:
  103. If one or more encodings have been applied to a representation, the
  104. sender that applied the encodings MUST generate a Content-Encoding
  105. header field that lists the content codings in the order in which
  106. they were applied.
  107. """
  108. def __init__(self, modes):
  109. self._decoders = [_get_decoder(m.strip()) for m in modes.split(",")]
  110. def flush(self):
  111. return self._decoders[0].flush()
  112. def decompress(self, data):
  113. for d in reversed(self._decoders):
  114. data = d.decompress(data)
  115. return data
  116. def _get_decoder(mode):
  117. if "," in mode:
  118. return MultiDecoder(mode)
  119. if mode == "gzip":
  120. return GzipDecoder()
  121. if brotli is not None and mode == "br":
  122. return BrotliDecoder()
  123. return DeflateDecoder()
  124. class HTTPResponse(io.IOBase):
  125. """
  126. HTTP Response container.
  127. Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is
  128. loaded and decoded on-demand when the ``data`` property is accessed. This
  129. class is also compatible with the Python standard library's :mod:`io`
  130. module, and can hence be treated as a readable object in the context of that
  131. framework.
  132. Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`:
  133. :param preload_content:
  134. If True, the response's body will be preloaded during construction.
  135. :param decode_content:
  136. If True, will attempt to decode the body based on the
  137. 'content-encoding' header.
  138. :param original_response:
  139. When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse`
  140. object, it's convenient to include the original for debug purposes. It's
  141. otherwise unused.
  142. :param retries:
  143. The retries contains the last :class:`~urllib3.util.retry.Retry` that
  144. was used during the request.
  145. :param enforce_content_length:
  146. Enforce content length checking. Body returned by server must match
  147. value of Content-Length header, if present. Otherwise, raise error.
  148. """
  149. CONTENT_DECODERS = ["gzip", "deflate"]
  150. if brotli is not None:
  151. CONTENT_DECODERS += ["br"]
  152. REDIRECT_STATUSES = [301, 302, 303, 307, 308]
  153. def __init__(
  154. self,
  155. body="",
  156. headers=None,
  157. status=0,
  158. version=0,
  159. reason=None,
  160. strict=0,
  161. preload_content=True,
  162. decode_content=True,
  163. original_response=None,
  164. pool=None,
  165. connection=None,
  166. msg=None,
  167. retries=None,
  168. enforce_content_length=False,
  169. request_method=None,
  170. request_url=None,
  171. auto_close=True,
  172. ):
  173. if isinstance(headers, HTTPHeaderDict):
  174. self.headers = headers
  175. else:
  176. self.headers = HTTPHeaderDict(headers)
  177. self.status = status
  178. self.version = version
  179. self.reason = reason
  180. self.strict = strict
  181. self.decode_content = decode_content
  182. self.retries = retries
  183. self.enforce_content_length = enforce_content_length
  184. self.auto_close = auto_close
  185. self._decoder = None
  186. self._body = None
  187. self._fp = None
  188. self._original_response = original_response
  189. self._fp_bytes_read = 0
  190. self.msg = msg
  191. self._request_url = request_url
  192. if body and isinstance(body, (six.string_types, bytes)):
  193. self._body = body
  194. self._pool = pool
  195. self._connection = connection
  196. if hasattr(body, "read"):
  197. self._fp = body
  198. # Are we using the chunked-style of transfer encoding?
  199. self.chunked = False
  200. self.chunk_left = None
  201. tr_enc = self.headers.get("transfer-encoding", "").lower()
  202. # Don't incur the penalty of creating a list and then discarding it
  203. encodings = (enc.strip() for enc in tr_enc.split(","))
  204. if "chunked" in encodings:
  205. self.chunked = True
  206. # Determine length of response
  207. self.length_remaining = self._init_length(request_method)
  208. # If requested, preload the body.
  209. if preload_content and not self._body:
  210. self._body = self.read(decode_content=decode_content)
  211. def get_redirect_location(self):
  212. """
  213. Should we redirect and where to?
  214. :returns: Truthy redirect location string if we got a redirect status
  215. code and valid location. ``None`` if redirect status and no
  216. location. ``False`` if not a redirect status code.
  217. """
  218. if self.status in self.REDIRECT_STATUSES:
  219. return self.headers.get("location")
  220. return False
  221. def release_conn(self):
  222. if not self._pool or not self._connection:
  223. return
  224. self._pool._put_conn(self._connection)
  225. self._connection = None
  226. def drain_conn(self):
  227. """
  228. Read and discard any remaining HTTP response data in the response connection.
  229. Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.
  230. """
  231. try:
  232. self.read()
  233. except (HTTPError, SocketError, BaseSSLError, HTTPException):
  234. pass
  235. @property
  236. def data(self):
  237. # For backwards-compat with earlier urllib3 0.4 and earlier.
  238. if self._body:
  239. return self._body
  240. if self._fp:
  241. return self.read(cache_content=True)
  242. @property
  243. def connection(self):
  244. return self._connection
  245. def isclosed(self):
  246. return is_fp_closed(self._fp)
  247. def tell(self):
  248. """
  249. Obtain the number of bytes pulled over the wire so far. May differ from
  250. the amount of content returned by :meth:``urllib3.response.HTTPResponse.read``
  251. if bytes are encoded on the wire (e.g, compressed).
  252. """
  253. return self._fp_bytes_read
  254. def _init_length(self, request_method):
  255. """
  256. Set initial length value for Response content if available.
  257. """
  258. length = self.headers.get("content-length")
  259. if length is not None:
  260. if self.chunked:
  261. # This Response will fail with an IncompleteRead if it can't be
  262. # received as chunked. This method falls back to attempt reading
  263. # the response before raising an exception.
  264. log.warning(
  265. "Received response with both Content-Length and "
  266. "Transfer-Encoding set. This is expressly forbidden "
  267. "by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
  268. "attempting to process response as Transfer-Encoding: "
  269. "chunked."
  270. )
  271. return None
  272. try:
  273. # RFC 7230 section 3.3.2 specifies multiple content lengths can
  274. # be sent in a single Content-Length header
  275. # (e.g. Content-Length: 42, 42). This line ensures the values
  276. # are all valid ints and that as long as the `set` length is 1,
  277. # all values are the same. Otherwise, the header is invalid.
  278. lengths = set([int(val) for val in length.split(",")])
  279. if len(lengths) > 1:
  280. raise InvalidHeader(
  281. "Content-Length contained multiple "
  282. "unmatching values (%s)" % length
  283. )
  284. length = lengths.pop()
  285. except ValueError:
  286. length = None
  287. else:
  288. if length < 0:
  289. length = None
  290. # Convert status to int for comparison
  291. # In some cases, httplib returns a status of "_UNKNOWN"
  292. try:
  293. status = int(self.status)
  294. except ValueError:
  295. status = 0
  296. # Check for responses that shouldn't include a body
  297. if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD":
  298. length = 0
  299. return length
  300. def _init_decoder(self):
  301. """
  302. Set-up the _decoder attribute if necessary.
  303. """
  304. # Note: content-encoding value should be case-insensitive, per RFC 7230
  305. # Section 3.2
  306. content_encoding = self.headers.get("content-encoding", "").lower()
  307. if self._decoder is None:
  308. if content_encoding in self.CONTENT_DECODERS:
  309. self._decoder = _get_decoder(content_encoding)
  310. elif "," in content_encoding:
  311. encodings = [
  312. e.strip()
  313. for e in content_encoding.split(",")
  314. if e.strip() in self.CONTENT_DECODERS
  315. ]
  316. if len(encodings):
  317. self._decoder = _get_decoder(content_encoding)
  318. DECODER_ERROR_CLASSES = (IOError, zlib.error)
  319. if brotli is not None:
  320. DECODER_ERROR_CLASSES += (brotli.error,)
  321. def _decode(self, data, decode_content, flush_decoder):
  322. """
  323. Decode the data passed in and potentially flush the decoder.
  324. """
  325. if not decode_content:
  326. return data
  327. try:
  328. if self._decoder:
  329. data = self._decoder.decompress(data)
  330. except self.DECODER_ERROR_CLASSES as e:
  331. content_encoding = self.headers.get("content-encoding", "").lower()
  332. raise DecodeError(
  333. "Received response with content-encoding: %s, but "
  334. "failed to decode it." % content_encoding,
  335. e,
  336. )
  337. if flush_decoder:
  338. data += self._flush_decoder()
  339. return data
  340. def _flush_decoder(self):
  341. """
  342. Flushes the decoder. Should only be called if the decoder is actually
  343. being used.
  344. """
  345. if self._decoder:
  346. buf = self._decoder.decompress(b"")
  347. return buf + self._decoder.flush()
  348. return b""
  349. @contextmanager
  350. def _error_catcher(self):
  351. """
  352. Catch low-level python exceptions, instead re-raising urllib3
  353. variants, so that low-level exceptions are not leaked in the
  354. high-level api.
  355. On exit, release the connection back to the pool.
  356. """
  357. clean_exit = False
  358. try:
  359. try:
  360. yield
  361. except SocketTimeout:
  362. # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
  363. # there is yet no clean way to get at it from this context.
  364. raise ReadTimeoutError(self._pool, None, "Read timed out.")
  365. except BaseSSLError as e:
  366. # FIXME: Is there a better way to differentiate between SSLErrors?
  367. if "read operation timed out" not in str(e):
  368. # SSL errors related to framing/MAC get wrapped and reraised here
  369. raise SSLError(e)
  370. raise ReadTimeoutError(self._pool, None, "Read timed out.")
  371. except (HTTPException, SocketError) as e:
  372. # This includes IncompleteRead.
  373. raise ProtocolError("Connection broken: %r" % e, e)
  374. # If no exception is thrown, we should avoid cleaning up
  375. # unnecessarily.
  376. clean_exit = True
  377. finally:
  378. # If we didn't terminate cleanly, we need to throw away our
  379. # connection.
  380. if not clean_exit:
  381. # The response may not be closed but we're not going to use it
  382. # anymore so close it now to ensure that the connection is
  383. # released back to the pool.
  384. if self._original_response:
  385. self._original_response.close()
  386. # Closing the response may not actually be sufficient to close
  387. # everything, so if we have a hold of the connection close that
  388. # too.
  389. if self._connection:
  390. self._connection.close()
  391. # If we hold the original response but it's closed now, we should
  392. # return the connection back to the pool.
  393. if self._original_response and self._original_response.isclosed():
  394. self.release_conn()
  395. def _fp_read(self, amt):
  396. """
  397. Read a response with the thought that reading the number of bytes
  398. larger than can fit in a 32-bit int at a time via SSL in some
  399. known cases leads to an overflow error that has to be prevented
  400. if `amt` or `self.length_remaining` indicate that a problem may
  401. happen.
  402. The known cases:
  403. * 3.8 <= CPython < 3.9.7 because of a bug
  404. https://github.com/urllib3/urllib3/issues/2513#issuecomment-1152559900.
  405. * urllib3 injected with pyOpenSSL-backed SSL-support.
  406. * CPython < 3.10 only when `amt` does not fit 32-bit int.
  407. """
  408. assert self._fp
  409. c_int_max = 2 ** 31 - 1
  410. if (
  411. (
  412. (amt and amt > c_int_max)
  413. or (self.length_remaining and self.length_remaining > c_int_max)
  414. )
  415. and not util.IS_SECURETRANSPORT
  416. and (util.IS_PYOPENSSL or sys.version_info < (3, 10))
  417. ):
  418. buffer = io.BytesIO()
  419. # Besides `max_chunk_amt` being a maximum chunk size, it
  420. # affects memory overhead of reading a response by this
  421. # method in CPython.
  422. # `c_int_max` equal to 2 GiB - 1 byte is the actual maximum
  423. # chunk size that does not lead to an overflow error, but
  424. # 256 MiB is a compromise.
  425. max_chunk_amt = 2 ** 28
  426. while amt is None or amt != 0:
  427. if amt is not None:
  428. chunk_amt = min(amt, max_chunk_amt)
  429. amt -= chunk_amt
  430. else:
  431. chunk_amt = max_chunk_amt
  432. data = self._fp.read(chunk_amt)
  433. if not data:
  434. break
  435. buffer.write(data)
  436. del data # to reduce peak memory usage by `max_chunk_amt`.
  437. return buffer.getvalue()
  438. else:
  439. # StringIO doesn't like amt=None
  440. return self._fp.read(amt) if amt is not None else self._fp.read()
  441. def read(self, amt=None, decode_content=None, cache_content=False):
  442. """
  443. Similar to :meth:`http.client.HTTPResponse.read`, but with two additional
  444. parameters: ``decode_content`` and ``cache_content``.
  445. :param amt:
  446. How much of the content to read. If specified, caching is skipped
  447. because it doesn't make sense to cache partial content as the full
  448. response.
  449. :param decode_content:
  450. If True, will attempt to decode the body based on the
  451. 'content-encoding' header.
  452. :param cache_content:
  453. If True, will save the returned data such that the same result is
  454. returned despite of the state of the underlying file object. This
  455. is useful if you want the ``.data`` property to continue working
  456. after having ``.read()`` the file object. (Overridden if ``amt`` is
  457. set.)
  458. """
  459. self._init_decoder()
  460. if decode_content is None:
  461. decode_content = self.decode_content
  462. if self._fp is None:
  463. return
  464. flush_decoder = False
  465. fp_closed = getattr(self._fp, "closed", False)
  466. with self._error_catcher():
  467. data = self._fp_read(amt) if not fp_closed else b""
  468. if amt is None:
  469. flush_decoder = True
  470. else:
  471. cache_content = False
  472. if (
  473. amt != 0 and not data
  474. ): # Platform-specific: Buggy versions of Python.
  475. # Close the connection when no data is returned
  476. #
  477. # This is redundant to what httplib/http.client _should_
  478. # already do. However, versions of python released before
  479. # December 15, 2012 (http://bugs.python.org/issue16298) do
  480. # not properly close the connection in all cases. There is
  481. # no harm in redundantly calling close.
  482. self._fp.close()
  483. flush_decoder = True
  484. if self.enforce_content_length and self.length_remaining not in (
  485. 0,
  486. None,
  487. ):
  488. # This is an edge case that httplib failed to cover due
  489. # to concerns of backward compatibility. We're
  490. # addressing it here to make sure IncompleteRead is
  491. # raised during streaming, so all calls with incorrect
  492. # Content-Length are caught.
  493. raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  494. if data:
  495. self._fp_bytes_read += len(data)
  496. if self.length_remaining is not None:
  497. self.length_remaining -= len(data)
  498. data = self._decode(data, decode_content, flush_decoder)
  499. if cache_content:
  500. self._body = data
  501. return data
  502. def stream(self, amt=2 ** 16, decode_content=None):
  503. """
  504. A generator wrapper for the read() method. A call will block until
  505. ``amt`` bytes have been read from the connection or until the
  506. connection is closed.
  507. :param amt:
  508. How much of the content to read. The generator will return up to
  509. much data per iteration, but may return less. This is particularly
  510. likely when using compressed data. However, the empty string will
  511. never be returned.
  512. :param decode_content:
  513. If True, will attempt to decode the body based on the
  514. 'content-encoding' header.
  515. """
  516. if self.chunked and self.supports_chunked_reads():
  517. for line in self.read_chunked(amt, decode_content=decode_content):
  518. yield line
  519. else:
  520. while not is_fp_closed(self._fp):
  521. data = self.read(amt=amt, decode_content=decode_content)
  522. if data:
  523. yield data
  524. @classmethod
  525. def from_httplib(ResponseCls, r, **response_kw):
  526. """
  527. Given an :class:`http.client.HTTPResponse` instance ``r``, return a
  528. corresponding :class:`urllib3.response.HTTPResponse` object.
  529. Remaining parameters are passed to the HTTPResponse constructor, along
  530. with ``original_response=r``.
  531. """
  532. headers = r.msg
  533. if not isinstance(headers, HTTPHeaderDict):
  534. if six.PY2:
  535. # Python 2.7
  536. headers = HTTPHeaderDict.from_httplib(headers)
  537. else:
  538. headers = HTTPHeaderDict(headers.items())
  539. # HTTPResponse objects in Python 3 don't have a .strict attribute
  540. strict = getattr(r, "strict", 0)
  541. resp = ResponseCls(
  542. body=r,
  543. headers=headers,
  544. status=r.status,
  545. version=r.version,
  546. reason=r.reason,
  547. strict=strict,
  548. original_response=r,
  549. **response_kw
  550. )
  551. return resp
  552. # Backwards-compatibility methods for http.client.HTTPResponse
  553. def getheaders(self):
  554. warnings.warn(
  555. "HTTPResponse.getheaders() is deprecated and will be removed "
  556. "in urllib3 v2.1.0. Instead access HTTPResponse.headers directly.",
  557. category=DeprecationWarning,
  558. stacklevel=2,
  559. )
  560. return self.headers
  561. def getheader(self, name, default=None):
  562. warnings.warn(
  563. "HTTPResponse.getheader() is deprecated and will be removed "
  564. "in urllib3 v2.1.0. Instead use HTTPResponse.headers.get(name, default).",
  565. category=DeprecationWarning,
  566. stacklevel=2,
  567. )
  568. return self.headers.get(name, default)
  569. # Backwards compatibility for http.cookiejar
  570. def info(self):
  571. return self.headers
  572. # Overrides from io.IOBase
  573. def close(self):
  574. if not self.closed:
  575. self._fp.close()
  576. if self._connection:
  577. self._connection.close()
  578. if not self.auto_close:
  579. io.IOBase.close(self)
  580. @property
  581. def closed(self):
  582. if not self.auto_close:
  583. return io.IOBase.closed.__get__(self)
  584. elif self._fp is None:
  585. return True
  586. elif hasattr(self._fp, "isclosed"):
  587. return self._fp.isclosed()
  588. elif hasattr(self._fp, "closed"):
  589. return self._fp.closed
  590. else:
  591. return True
  592. def fileno(self):
  593. if self._fp is None:
  594. raise IOError("HTTPResponse has no file to get a fileno from")
  595. elif hasattr(self._fp, "fileno"):
  596. return self._fp.fileno()
  597. else:
  598. raise IOError(
  599. "The file-like object this HTTPResponse is wrapped "
  600. "around has no file descriptor"
  601. )
  602. def flush(self):
  603. if (
  604. self._fp is not None
  605. and hasattr(self._fp, "flush")
  606. and not getattr(self._fp, "closed", False)
  607. ):
  608. return self._fp.flush()
  609. def readable(self):
  610. # This method is required for `io` module compatibility.
  611. return True
  612. def readinto(self, b):
  613. # This method is required for `io` module compatibility.
  614. temp = self.read(len(b))
  615. if len(temp) == 0:
  616. return 0
  617. else:
  618. b[: len(temp)] = temp
  619. return len(temp)
  620. def supports_chunked_reads(self):
  621. """
  622. Checks if the underlying file-like object looks like a
  623. :class:`http.client.HTTPResponse` object. We do this by testing for
  624. the fp attribute. If it is present we assume it returns raw chunks as
  625. processed by read_chunked().
  626. """
  627. return hasattr(self._fp, "fp")
  628. def _update_chunk_length(self):
  629. # First, we'll figure out length of a chunk and then
  630. # we'll try to read it from socket.
  631. if self.chunk_left is not None:
  632. return
  633. line = self._fp.fp.readline()
  634. line = line.split(b";", 1)[0]
  635. try:
  636. self.chunk_left = int(line, 16)
  637. except ValueError:
  638. # Invalid chunked protocol response, abort.
  639. self.close()
  640. raise InvalidChunkLength(self, line)
  641. def _handle_chunk(self, amt):
  642. returned_chunk = None
  643. if amt is None:
  644. chunk = self._fp._safe_read(self.chunk_left)
  645. returned_chunk = chunk
  646. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  647. self.chunk_left = None
  648. elif amt < self.chunk_left:
  649. value = self._fp._safe_read(amt)
  650. self.chunk_left = self.chunk_left - amt
  651. returned_chunk = value
  652. elif amt == self.chunk_left:
  653. value = self._fp._safe_read(amt)
  654. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  655. self.chunk_left = None
  656. returned_chunk = value
  657. else: # amt > self.chunk_left
  658. returned_chunk = self._fp._safe_read(self.chunk_left)
  659. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  660. self.chunk_left = None
  661. return returned_chunk
  662. def read_chunked(self, amt=None, decode_content=None):
  663. """
  664. Similar to :meth:`HTTPResponse.read`, but with an additional
  665. parameter: ``decode_content``.
  666. :param amt:
  667. How much of the content to read. If specified, caching is skipped
  668. because it doesn't make sense to cache partial content as the full
  669. response.
  670. :param decode_content:
  671. If True, will attempt to decode the body based on the
  672. 'content-encoding' header.
  673. """
  674. self._init_decoder()
  675. # FIXME: Rewrite this method and make it a class with a better structured logic.
  676. if not self.chunked:
  677. raise ResponseNotChunked(
  678. "Response is not chunked. "
  679. "Header 'transfer-encoding: chunked' is missing."
  680. )
  681. if not self.supports_chunked_reads():
  682. raise BodyNotHttplibCompatible(
  683. "Body should be http.client.HTTPResponse like. "
  684. "It should have have an fp attribute which returns raw chunks."
  685. )
  686. with self._error_catcher():
  687. # Don't bother reading the body of a HEAD request.
  688. if self._original_response and is_response_to_head(self._original_response):
  689. self._original_response.close()
  690. return
  691. # If a response is already read and closed
  692. # then return immediately.
  693. if self._fp.fp is None:
  694. return
  695. while True:
  696. self._update_chunk_length()
  697. if self.chunk_left == 0:
  698. break
  699. chunk = self._handle_chunk(amt)
  700. decoded = self._decode(
  701. chunk, decode_content=decode_content, flush_decoder=False
  702. )
  703. if decoded:
  704. yield decoded
  705. if decode_content:
  706. # On CPython and PyPy, we should never need to flush the
  707. # decoder. However, on Jython we *might* need to, so
  708. # lets defensively do it anyway.
  709. decoded = self._flush_decoder()
  710. if decoded: # Platform-specific: Jython.
  711. yield decoded
  712. # Chunk content ends with \r\n: discard it.
  713. while True:
  714. line = self._fp.fp.readline()
  715. if not line:
  716. # Some sites may not end with '\r\n'.
  717. break
  718. if line == b"\r\n":
  719. break
  720. # We read everything; close the "file".
  721. if self._original_response:
  722. self._original_response.close()
  723. def geturl(self):
  724. """
  725. Returns the URL that was the source of this response.
  726. If the request that generated this response redirected, this method
  727. will return the final redirect location.
  728. """
  729. if self.retries is not None and len(self.retries.history):
  730. return self.retries.history[-1].redirect_location
  731. else:
  732. return self._request_url
  733. def __iter__(self):
  734. buffer = []
  735. for chunk in self.stream(decode_content=True):
  736. if b"\n" in chunk:
  737. chunk = chunk.split(b"\n")
  738. yield b"".join(buffer) + chunk[0] + b"\n"
  739. for x in chunk[1:-1]:
  740. yield x + b"\n"
  741. if chunk[-1]:
  742. buffer = [chunk[-1]]
  743. else:
  744. buffer = []
  745. else:
  746. buffer.append(chunk)
  747. if buffer:
  748. yield b"".join(buffer)