Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

response.py 24KB

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