response.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. from __future__ import absolute_import
  2. import io
  3. import logging
  4. import zlib
  5. from contextlib import contextmanager
  6. from socket import error as SocketError
  7. from socket import timeout as SocketTimeout
  8. try:
  9. import brotli
  10. except ImportError:
  11. brotli = None
  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 read(self, amt=None, decode_content=None, cache_content=False):
  396. """
  397. Similar to :meth:`http.client.HTTPResponse.read`, but with two additional
  398. parameters: ``decode_content`` and ``cache_content``.
  399. :param amt:
  400. How much of the content to read. If specified, caching is skipped
  401. because it doesn't make sense to cache partial content as the full
  402. response.
  403. :param decode_content:
  404. If True, will attempt to decode the body based on the
  405. 'content-encoding' header.
  406. :param cache_content:
  407. If True, will save the returned data such that the same result is
  408. returned despite of the state of the underlying file object. This
  409. is useful if you want the ``.data`` property to continue working
  410. after having ``.read()`` the file object. (Overridden if ``amt`` is
  411. set.)
  412. """
  413. self._init_decoder()
  414. if decode_content is None:
  415. decode_content = self.decode_content
  416. if self._fp is None:
  417. return
  418. flush_decoder = False
  419. fp_closed = getattr(self._fp, "closed", False)
  420. with self._error_catcher():
  421. if amt is None:
  422. # cStringIO doesn't like amt=None
  423. data = self._fp.read() if not fp_closed else b""
  424. flush_decoder = True
  425. else:
  426. cache_content = False
  427. data = self._fp.read(amt) if not fp_closed else b""
  428. if (
  429. amt != 0 and not data
  430. ): # Platform-specific: Buggy versions of Python.
  431. # Close the connection when no data is returned
  432. #
  433. # This is redundant to what httplib/http.client _should_
  434. # already do. However, versions of python released before
  435. # December 15, 2012 (http://bugs.python.org/issue16298) do
  436. # not properly close the connection in all cases. There is
  437. # no harm in redundantly calling close.
  438. self._fp.close()
  439. flush_decoder = True
  440. if self.enforce_content_length and self.length_remaining not in (
  441. 0,
  442. None,
  443. ):
  444. # This is an edge case that httplib failed to cover due
  445. # to concerns of backward compatibility. We're
  446. # addressing it here to make sure IncompleteRead is
  447. # raised during streaming, so all calls with incorrect
  448. # Content-Length are caught.
  449. raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  450. if data:
  451. self._fp_bytes_read += len(data)
  452. if self.length_remaining is not None:
  453. self.length_remaining -= len(data)
  454. data = self._decode(data, decode_content, flush_decoder)
  455. if cache_content:
  456. self._body = data
  457. return data
  458. def stream(self, amt=2 ** 16, decode_content=None):
  459. """
  460. A generator wrapper for the read() method. A call will block until
  461. ``amt`` bytes have been read from the connection or until the
  462. connection is closed.
  463. :param amt:
  464. How much of the content to read. The generator will return up to
  465. much data per iteration, but may return less. This is particularly
  466. likely when using compressed data. However, the empty string will
  467. never be returned.
  468. :param decode_content:
  469. If True, will attempt to decode the body based on the
  470. 'content-encoding' header.
  471. """
  472. if self.chunked and self.supports_chunked_reads():
  473. for line in self.read_chunked(amt, decode_content=decode_content):
  474. yield line
  475. else:
  476. while not is_fp_closed(self._fp):
  477. data = self.read(amt=amt, decode_content=decode_content)
  478. if data:
  479. yield data
  480. @classmethod
  481. def from_httplib(ResponseCls, r, **response_kw):
  482. """
  483. Given an :class:`http.client.HTTPResponse` instance ``r``, return a
  484. corresponding :class:`urllib3.response.HTTPResponse` object.
  485. Remaining parameters are passed to the HTTPResponse constructor, along
  486. with ``original_response=r``.
  487. """
  488. headers = r.msg
  489. if not isinstance(headers, HTTPHeaderDict):
  490. if six.PY2:
  491. # Python 2.7
  492. headers = HTTPHeaderDict.from_httplib(headers)
  493. else:
  494. headers = HTTPHeaderDict(headers.items())
  495. # HTTPResponse objects in Python 3 don't have a .strict attribute
  496. strict = getattr(r, "strict", 0)
  497. resp = ResponseCls(
  498. body=r,
  499. headers=headers,
  500. status=r.status,
  501. version=r.version,
  502. reason=r.reason,
  503. strict=strict,
  504. original_response=r,
  505. **response_kw
  506. )
  507. return resp
  508. # Backwards-compatibility methods for http.client.HTTPResponse
  509. def getheaders(self):
  510. return self.headers
  511. def getheader(self, name, default=None):
  512. return self.headers.get(name, default)
  513. # Backwards compatibility for http.cookiejar
  514. def info(self):
  515. return self.headers
  516. # Overrides from io.IOBase
  517. def close(self):
  518. if not self.closed:
  519. self._fp.close()
  520. if self._connection:
  521. self._connection.close()
  522. if not self.auto_close:
  523. io.IOBase.close(self)
  524. @property
  525. def closed(self):
  526. if not self.auto_close:
  527. return io.IOBase.closed.__get__(self)
  528. elif self._fp is None:
  529. return True
  530. elif hasattr(self._fp, "isclosed"):
  531. return self._fp.isclosed()
  532. elif hasattr(self._fp, "closed"):
  533. return self._fp.closed
  534. else:
  535. return True
  536. def fileno(self):
  537. if self._fp is None:
  538. raise IOError("HTTPResponse has no file to get a fileno from")
  539. elif hasattr(self._fp, "fileno"):
  540. return self._fp.fileno()
  541. else:
  542. raise IOError(
  543. "The file-like object this HTTPResponse is wrapped "
  544. "around has no file descriptor"
  545. )
  546. def flush(self):
  547. if (
  548. self._fp is not None
  549. and hasattr(self._fp, "flush")
  550. and not getattr(self._fp, "closed", False)
  551. ):
  552. return self._fp.flush()
  553. def readable(self):
  554. # This method is required for `io` module compatibility.
  555. return True
  556. def readinto(self, b):
  557. # This method is required for `io` module compatibility.
  558. temp = self.read(len(b))
  559. if len(temp) == 0:
  560. return 0
  561. else:
  562. b[: len(temp)] = temp
  563. return len(temp)
  564. def supports_chunked_reads(self):
  565. """
  566. Checks if the underlying file-like object looks like a
  567. :class:`http.client.HTTPResponse` object. We do this by testing for
  568. the fp attribute. If it is present we assume it returns raw chunks as
  569. processed by read_chunked().
  570. """
  571. return hasattr(self._fp, "fp")
  572. def _update_chunk_length(self):
  573. # First, we'll figure out length of a chunk and then
  574. # we'll try to read it from socket.
  575. if self.chunk_left is not None:
  576. return
  577. line = self._fp.fp.readline()
  578. line = line.split(b";", 1)[0]
  579. try:
  580. self.chunk_left = int(line, 16)
  581. except ValueError:
  582. # Invalid chunked protocol response, abort.
  583. self.close()
  584. raise InvalidChunkLength(self, line)
  585. def _handle_chunk(self, amt):
  586. returned_chunk = None
  587. if amt is None:
  588. chunk = self._fp._safe_read(self.chunk_left)
  589. returned_chunk = chunk
  590. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  591. self.chunk_left = None
  592. elif amt < self.chunk_left:
  593. value = self._fp._safe_read(amt)
  594. self.chunk_left = self.chunk_left - amt
  595. returned_chunk = value
  596. elif amt == self.chunk_left:
  597. value = self._fp._safe_read(amt)
  598. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  599. self.chunk_left = None
  600. returned_chunk = value
  601. else: # amt > self.chunk_left
  602. returned_chunk = self._fp._safe_read(self.chunk_left)
  603. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  604. self.chunk_left = None
  605. return returned_chunk
  606. def read_chunked(self, amt=None, decode_content=None):
  607. """
  608. Similar to :meth:`HTTPResponse.read`, but with an additional
  609. parameter: ``decode_content``.
  610. :param amt:
  611. How much of the content to read. If specified, caching is skipped
  612. because it doesn't make sense to cache partial content as the full
  613. response.
  614. :param decode_content:
  615. If True, will attempt to decode the body based on the
  616. 'content-encoding' header.
  617. """
  618. self._init_decoder()
  619. # FIXME: Rewrite this method and make it a class with a better structured logic.
  620. if not self.chunked:
  621. raise ResponseNotChunked(
  622. "Response is not chunked. "
  623. "Header 'transfer-encoding: chunked' is missing."
  624. )
  625. if not self.supports_chunked_reads():
  626. raise BodyNotHttplibCompatible(
  627. "Body should be http.client.HTTPResponse like. "
  628. "It should have have an fp attribute which returns raw chunks."
  629. )
  630. with self._error_catcher():
  631. # Don't bother reading the body of a HEAD request.
  632. if self._original_response and is_response_to_head(self._original_response):
  633. self._original_response.close()
  634. return
  635. # If a response is already read and closed
  636. # then return immediately.
  637. if self._fp.fp is None:
  638. return
  639. while True:
  640. self._update_chunk_length()
  641. if self.chunk_left == 0:
  642. break
  643. chunk = self._handle_chunk(amt)
  644. decoded = self._decode(
  645. chunk, decode_content=decode_content, flush_decoder=False
  646. )
  647. if decoded:
  648. yield decoded
  649. if decode_content:
  650. # On CPython and PyPy, we should never need to flush the
  651. # decoder. However, on Jython we *might* need to, so
  652. # lets defensively do it anyway.
  653. decoded = self._flush_decoder()
  654. if decoded: # Platform-specific: Jython.
  655. yield decoded
  656. # Chunk content ends with \r\n: discard it.
  657. while True:
  658. line = self._fp.fp.readline()
  659. if not line:
  660. # Some sites may not end with '\r\n'.
  661. break
  662. if line == b"\r\n":
  663. break
  664. # We read everything; close the "file".
  665. if self._original_response:
  666. self._original_response.close()
  667. def geturl(self):
  668. """
  669. Returns the URL that was the source of this response.
  670. If the request that generated this response redirected, this method
  671. will return the final redirect location.
  672. """
  673. if self.retries is not None and len(self.retries.history):
  674. return self.retries.history[-1].redirect_location
  675. else:
  676. return self._request_url
  677. def __iter__(self):
  678. buffer = []
  679. for chunk in self.stream(decode_content=True):
  680. if b"\n" in chunk:
  681. chunk = chunk.split(b"\n")
  682. yield b"".join(buffer) + chunk[0] + b"\n"
  683. for x in chunk[1:-1]:
  684. yield x + b"\n"
  685. if chunk[-1]:
  686. buffer = [chunk[-1]]
  687. else:
  688. buffer = []
  689. else:
  690. buffer.append(chunk)
  691. if buffer:
  692. yield b"".join(buffer)