response.py 27 KB

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