response.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. from __future__ import absolute_import
  2. from contextlib import contextmanager
  3. import zlib
  4. import io
  5. import logging
  6. from socket import timeout as SocketTimeout
  7. from socket import error as SocketError
  8. try:
  9. import brotli
  10. except ImportError:
  11. brotli = None
  12. from ._collections import HTTPHeaderDict
  13. from .exceptions import (
  14. BodyNotHttplibCompatible,
  15. ProtocolError,
  16. DecodeError,
  17. ReadTimeoutError,
  18. ResponseNotChunked,
  19. IncompleteRead,
  20. InvalidHeader,
  21. HTTPError,
  22. )
  23. from .packages.six import string_types as basestring, PY3
  24. from .packages.six.moves import http_client as httplib
  25. from .connection import HTTPException, BaseSSLError
  26. from .util.response import is_fp_closed, is_response_to_head
  27. log = logging.getLogger(__name__)
  28. class DeflateDecoder(object):
  29. def __init__(self):
  30. self._first_try = True
  31. self._data = b""
  32. self._obj = zlib.decompressobj()
  33. def __getattr__(self, name):
  34. return getattr(self._obj, name)
  35. def decompress(self, data):
  36. if not data:
  37. return data
  38. if not self._first_try:
  39. return self._obj.decompress(data)
  40. self._data += data
  41. try:
  42. decompressed = self._obj.decompress(data)
  43. if decompressed:
  44. self._first_try = False
  45. self._data = None
  46. return decompressed
  47. except zlib.error:
  48. self._first_try = False
  49. self._obj = zlib.decompressobj(-zlib.MAX_WBITS)
  50. try:
  51. return self.decompress(self._data)
  52. finally:
  53. self._data = None
  54. class GzipDecoderState(object):
  55. FIRST_MEMBER = 0
  56. OTHER_MEMBERS = 1
  57. SWALLOW_DATA = 2
  58. class GzipDecoder(object):
  59. def __init__(self):
  60. self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
  61. self._state = GzipDecoderState.FIRST_MEMBER
  62. def __getattr__(self, name):
  63. return getattr(self._obj, name)
  64. def decompress(self, data):
  65. ret = bytearray()
  66. if self._state == GzipDecoderState.SWALLOW_DATA or not data:
  67. return bytes(ret)
  68. while True:
  69. try:
  70. ret += self._obj.decompress(data)
  71. except zlib.error:
  72. previous_state = self._state
  73. # Ignore data after the first error
  74. self._state = GzipDecoderState.SWALLOW_DATA
  75. if previous_state == GzipDecoderState.OTHER_MEMBERS:
  76. # Allow trailing garbage acceptable in other gzip clients
  77. return bytes(ret)
  78. raise
  79. data = self._obj.unused_data
  80. if not data:
  81. return bytes(ret)
  82. self._state = GzipDecoderState.OTHER_MEMBERS
  83. self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
  84. if brotli is not None:
  85. class BrotliDecoder(object):
  86. # Supports both 'brotlipy' and 'Brotli' packages
  87. # since they share an import name. The top branches
  88. # are for 'brotlipy' and bottom branches for 'Brotli'
  89. def __init__(self):
  90. self._obj = brotli.Decompressor()
  91. def decompress(self, data):
  92. if hasattr(self._obj, "decompress"):
  93. return self._obj.decompress(data)
  94. return self._obj.process(data)
  95. def flush(self):
  96. if hasattr(self._obj, "flush"):
  97. return self._obj.flush()
  98. return b""
  99. class MultiDecoder(object):
  100. """
  101. From RFC7231:
  102. If one or more encodings have been applied to a representation, the
  103. sender that applied the encodings MUST generate a Content-Encoding
  104. header field that lists the content codings in the order in which
  105. they were applied.
  106. """
  107. def __init__(self, modes):
  108. self._decoders = [_get_decoder(m.strip()) for m in modes.split(",")]
  109. def flush(self):
  110. return self._decoders[0].flush()
  111. def decompress(self, data):
  112. for d in reversed(self._decoders):
  113. data = d.decompress(data)
  114. return data
  115. def _get_decoder(mode):
  116. if "," in mode:
  117. return MultiDecoder(mode)
  118. if mode == "gzip":
  119. return GzipDecoder()
  120. if brotli is not None and mode == "br":
  121. return BrotliDecoder()
  122. return DeflateDecoder()
  123. class HTTPResponse(io.IOBase):
  124. """
  125. HTTP Response container.
  126. Backwards-compatible to httplib's HTTPResponse but the response ``body`` is
  127. loaded and decoded on-demand when the ``data`` property is accessed. This
  128. class is also compatible with the Python standard library's :mod:`io`
  129. module, and can hence be treated as a readable object in the context of that
  130. framework.
  131. Extra parameters for behaviour not present in httplib.HTTPResponse:
  132. :param preload_content:
  133. If True, the response's body will be preloaded during construction.
  134. :param decode_content:
  135. If True, will attempt to decode the body based on the
  136. 'content-encoding' header.
  137. :param original_response:
  138. When this HTTPResponse wrapper is generated from an httplib.HTTPResponse
  139. object, it's convenient to include the original for debug purposes. It's
  140. otherwise unused.
  141. :param retries:
  142. The retries contains the last :class:`~urllib3.util.retry.Retry` that
  143. was used during the request.
  144. :param enforce_content_length:
  145. Enforce content length checking. Body returned by server must match
  146. value of Content-Length header, if present. Otherwise, raise error.
  147. """
  148. CONTENT_DECODERS = ["gzip", "deflate"]
  149. if brotli is not None:
  150. CONTENT_DECODERS += ["br"]
  151. REDIRECT_STATUSES = [301, 302, 303, 307, 308]
  152. def __init__(
  153. self,
  154. body="",
  155. headers=None,
  156. status=0,
  157. version=0,
  158. reason=None,
  159. strict=0,
  160. preload_content=True,
  161. decode_content=True,
  162. original_response=None,
  163. pool=None,
  164. connection=None,
  165. msg=None,
  166. retries=None,
  167. enforce_content_length=False,
  168. request_method=None,
  169. request_url=None,
  170. auto_close=True,
  171. ):
  172. if isinstance(headers, HTTPHeaderDict):
  173. self.headers = headers
  174. else:
  175. self.headers = HTTPHeaderDict(headers)
  176. self.status = status
  177. self.version = version
  178. self.reason = reason
  179. self.strict = strict
  180. self.decode_content = decode_content
  181. self.retries = retries
  182. self.enforce_content_length = enforce_content_length
  183. self.auto_close = auto_close
  184. self._decoder = None
  185. self._body = None
  186. self._fp = None
  187. self._original_response = original_response
  188. self._fp_bytes_read = 0
  189. self.msg = msg
  190. self._request_url = request_url
  191. if body and isinstance(body, (basestring, bytes)):
  192. self._body = body
  193. self._pool = pool
  194. self._connection = connection
  195. if hasattr(body, "read"):
  196. self._fp = body
  197. # Are we using the chunked-style of transfer encoding?
  198. self.chunked = False
  199. self.chunk_left = None
  200. tr_enc = self.headers.get("transfer-encoding", "").lower()
  201. # Don't incur the penalty of creating a list and then discarding it
  202. encodings = (enc.strip() for enc in tr_enc.split(","))
  203. if "chunked" in encodings:
  204. self.chunked = True
  205. # Determine length of response
  206. self.length_remaining = self._init_length(request_method)
  207. # If requested, preload the body.
  208. if preload_content and not self._body:
  209. self._body = self.read(decode_content=decode_content)
  210. def get_redirect_location(self):
  211. """
  212. Should we redirect and where to?
  213. :returns: Truthy redirect location string if we got a redirect status
  214. code and valid location. ``None`` if redirect status and no
  215. location. ``False`` if not a redirect status code.
  216. """
  217. if self.status in self.REDIRECT_STATUSES:
  218. return self.headers.get("location")
  219. return False
  220. def release_conn(self):
  221. if not self._pool or not self._connection:
  222. return
  223. self._pool._put_conn(self._connection)
  224. self._connection = None
  225. def drain_conn(self):
  226. """
  227. Read and discard any remaining HTTP response data in the response connection.
  228. Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.
  229. """
  230. try:
  231. self.read()
  232. except (HTTPError, SocketError, BaseSSLError, HTTPException):
  233. pass
  234. @property
  235. def data(self):
  236. # For backwords-compat with earlier urllib3 0.4 and earlier.
  237. if self._body:
  238. return self._body
  239. if self._fp:
  240. return self.read(cache_content=True)
  241. @property
  242. def connection(self):
  243. return self._connection
  244. def isclosed(self):
  245. return is_fp_closed(self._fp)
  246. def tell(self):
  247. """
  248. Obtain the number of bytes pulled over the wire so far. May differ from
  249. the amount of content returned by :meth:``HTTPResponse.read`` if bytes
  250. are encoded on the wire (e.g, compressed).
  251. """
  252. return self._fp_bytes_read
  253. def _init_length(self, request_method):
  254. """
  255. Set initial length value for Response content if available.
  256. """
  257. length = self.headers.get("content-length")
  258. if length is not None:
  259. if self.chunked:
  260. # This Response will fail with an IncompleteRead if it can't be
  261. # received as chunked. This method falls back to attempt reading
  262. # the response before raising an exception.
  263. log.warning(
  264. "Received response with both Content-Length and "
  265. "Transfer-Encoding set. This is expressly forbidden "
  266. "by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
  267. "attempting to process response as Transfer-Encoding: "
  268. "chunked."
  269. )
  270. return None
  271. try:
  272. # RFC 7230 section 3.3.2 specifies multiple content lengths can
  273. # be sent in a single Content-Length header
  274. # (e.g. Content-Length: 42, 42). This line ensures the values
  275. # are all valid ints and that as long as the `set` length is 1,
  276. # all values are the same. Otherwise, the header is invalid.
  277. lengths = set([int(val) for val in length.split(",")])
  278. if len(lengths) > 1:
  279. raise InvalidHeader(
  280. "Content-Length contained multiple "
  281. "unmatching values (%s)" % length
  282. )
  283. length = lengths.pop()
  284. except ValueError:
  285. length = None
  286. else:
  287. if length < 0:
  288. length = None
  289. # Convert status to int for comparison
  290. # In some cases, httplib returns a status of "_UNKNOWN"
  291. try:
  292. status = int(self.status)
  293. except ValueError:
  294. status = 0
  295. # Check for responses that shouldn't include a body
  296. if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD":
  297. length = 0
  298. return length
  299. def _init_decoder(self):
  300. """
  301. Set-up the _decoder attribute if necessary.
  302. """
  303. # Note: content-encoding value should be case-insensitive, per RFC 7230
  304. # Section 3.2
  305. content_encoding = self.headers.get("content-encoding", "").lower()
  306. if self._decoder is None:
  307. if content_encoding in self.CONTENT_DECODERS:
  308. self._decoder = _get_decoder(content_encoding)
  309. elif "," in content_encoding:
  310. encodings = [
  311. e.strip()
  312. for e in content_encoding.split(",")
  313. if e.strip() in self.CONTENT_DECODERS
  314. ]
  315. if len(encodings):
  316. self._decoder = _get_decoder(content_encoding)
  317. DECODER_ERROR_CLASSES = (IOError, zlib.error)
  318. if brotli is not None:
  319. DECODER_ERROR_CLASSES += (brotli.error,)
  320. def _decode(self, data, decode_content, flush_decoder):
  321. """
  322. Decode the data passed in and potentially flush the decoder.
  323. """
  324. if not decode_content:
  325. return data
  326. try:
  327. if self._decoder:
  328. data = self._decoder.decompress(data)
  329. except self.DECODER_ERROR_CLASSES as e:
  330. content_encoding = self.headers.get("content-encoding", "").lower()
  331. raise DecodeError(
  332. "Received response with content-encoding: %s, but "
  333. "failed to decode it." % content_encoding,
  334. e,
  335. )
  336. if flush_decoder:
  337. data += self._flush_decoder()
  338. return data
  339. def _flush_decoder(self):
  340. """
  341. Flushes the decoder. Should only be called if the decoder is actually
  342. being used.
  343. """
  344. if self._decoder:
  345. buf = self._decoder.decompress(b"")
  346. return buf + self._decoder.flush()
  347. return b""
  348. @contextmanager
  349. def _error_catcher(self):
  350. """
  351. Catch low-level python exceptions, instead re-raising urllib3
  352. variants, so that low-level exceptions are not leaked in the
  353. high-level api.
  354. On exit, release the connection back to the pool.
  355. """
  356. clean_exit = False
  357. try:
  358. try:
  359. yield
  360. except SocketTimeout:
  361. # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
  362. # there is yet no clean way to get at it from this context.
  363. raise ReadTimeoutError(self._pool, None, "Read timed out.")
  364. except BaseSSLError as e:
  365. # FIXME: Is there a better way to differentiate between SSLErrors?
  366. if "read operation timed out" not in str(e): # Defensive:
  367. # This shouldn't happen but just in case we're missing an edge
  368. # case, let's avoid swallowing SSL errors.
  369. raise
  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:`httplib.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:`httplib.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 PY3:
  491. headers = HTTPHeaderDict(headers.items())
  492. else:
  493. # Python 2.7
  494. headers = HTTPHeaderDict.from_httplib(headers)
  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 httplib.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. httplib.HTTPResponse object. We do this by testing for the fp
  568. 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 httplib.IncompleteRead(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 httplib.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)