response.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. from __future__ import annotations
  2. import json as _json
  3. import logging
  4. import typing
  5. from contextlib import contextmanager
  6. from dataclasses import dataclass
  7. from http.client import HTTPException as HTTPException
  8. from io import BytesIO, IOBase
  9. from ...exceptions import InvalidHeader, TimeoutError
  10. from ...response import BaseHTTPResponse
  11. from ...util.retry import Retry
  12. from .request import EmscriptenRequest
  13. if typing.TYPE_CHECKING:
  14. from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection
  15. log = logging.getLogger(__name__)
  16. @dataclass
  17. class EmscriptenResponse:
  18. status_code: int
  19. headers: dict[str, str]
  20. body: IOBase | bytes
  21. request: EmscriptenRequest
  22. class EmscriptenHttpResponseWrapper(BaseHTTPResponse):
  23. def __init__(
  24. self,
  25. internal_response: EmscriptenResponse,
  26. url: str | None = None,
  27. connection: BaseHTTPConnection | BaseHTTPSConnection | None = None,
  28. ):
  29. self._pool = None # set by pool class
  30. self._body = None
  31. self._uncached_read_occurred = False
  32. self._response = internal_response
  33. self._url = url
  34. self._connection = connection
  35. self._closed = False
  36. super().__init__(
  37. headers=internal_response.headers,
  38. status=internal_response.status_code,
  39. request_url=url,
  40. version=0,
  41. version_string="HTTP/?",
  42. reason="",
  43. decode_content=True,
  44. )
  45. self.length_remaining = self._init_length(self._response.request.method)
  46. self.length_is_certain = False
  47. @property
  48. def url(self) -> str | None:
  49. return self._url
  50. @url.setter
  51. def url(self, url: str | None) -> None:
  52. self._url = url
  53. @property
  54. def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None:
  55. return self._connection
  56. @property
  57. def retries(self) -> Retry | None:
  58. return self._retries
  59. @retries.setter
  60. def retries(self, retries: Retry | None) -> None:
  61. # Override the request_url if retries has a redirect location.
  62. self._retries = retries
  63. def stream(
  64. self, amt: int | None = 2**16, decode_content: bool | None = None
  65. ) -> typing.Generator[bytes]:
  66. """
  67. A generator wrapper for the read() method. A call will block until
  68. ``amt`` bytes have been read from the connection or until the
  69. connection is closed.
  70. :param amt:
  71. How much of the content to read. The generator will return up to
  72. much data per iteration, but may return less. This is particularly
  73. likely when using compressed data. However, the empty string will
  74. never be returned.
  75. :param decode_content:
  76. If True, will attempt to decode the body based on the
  77. 'content-encoding' header.
  78. """
  79. while True:
  80. data = self.read(amt=amt, decode_content=decode_content)
  81. if data:
  82. yield data
  83. else:
  84. break
  85. def _init_length(self, request_method: str | None) -> int | None:
  86. length: int | None
  87. content_length: str | None = self.headers.get("content-length")
  88. if content_length is not None:
  89. try:
  90. # RFC 7230 section 3.3.2 specifies multiple content lengths can
  91. # be sent in a single Content-Length header
  92. # (e.g. Content-Length: 42, 42). This line ensures the values
  93. # are all valid ints and that as long as the `set` length is 1,
  94. # all values are the same. Otherwise, the header is invalid.
  95. lengths = {int(val) for val in content_length.split(",")}
  96. if len(lengths) > 1:
  97. raise InvalidHeader(
  98. "Content-Length contained multiple "
  99. "unmatching values (%s)" % content_length
  100. )
  101. length = lengths.pop()
  102. except ValueError:
  103. length = None
  104. else:
  105. if length < 0:
  106. length = None
  107. else: # if content_length is None
  108. length = None
  109. # Check for responses that shouldn't include a body
  110. if (
  111. self.status in (204, 304)
  112. or 100 <= self.status < 200
  113. or request_method == "HEAD"
  114. ):
  115. length = 0
  116. return length
  117. def read(
  118. self,
  119. amt: int | None = None,
  120. decode_content: bool | None = None, # ignored because browser decodes always
  121. cache_content: bool = False,
  122. ) -> bytes:
  123. if (
  124. self._closed
  125. or self._response is None
  126. or (isinstance(self._response.body, IOBase) and self._response.body.closed)
  127. ):
  128. return b""
  129. with self._error_catcher():
  130. # body has been preloaded as a string by XmlHttpRequest
  131. if not isinstance(self._response.body, IOBase):
  132. self.length_remaining = len(self._response.body)
  133. self.length_is_certain = True
  134. # wrap body in IOStream
  135. self._response.body = BytesIO(self._response.body)
  136. if amt is not None and amt >= 0:
  137. # don't cache partial content
  138. cache_content = False
  139. data = self._response.body.read(amt)
  140. self._uncached_read_occurred = True
  141. else: # read all we can (and cache it)
  142. data = self._response.body.read()
  143. if cache_content and not self._uncached_read_occurred:
  144. self._body = data
  145. else:
  146. self._uncached_read_occurred = True
  147. if self.length_remaining is not None:
  148. self.length_remaining = max(self.length_remaining - len(data), 0)
  149. if len(data) == 0 or (
  150. self.length_is_certain and self.length_remaining == 0
  151. ):
  152. # definitely finished reading, close response stream
  153. self._response.body.close()
  154. return typing.cast(bytes, data)
  155. def read_chunked(
  156. self,
  157. amt: int | None = None,
  158. decode_content: bool | None = None,
  159. ) -> typing.Generator[bytes]:
  160. # chunked is handled by browser
  161. while True:
  162. bytes = self.read(amt, decode_content)
  163. if not bytes:
  164. break
  165. yield bytes
  166. def release_conn(self) -> None:
  167. if not self._pool or not self._connection:
  168. return None
  169. self._pool._put_conn(self._connection)
  170. self._connection = None
  171. def drain_conn(self) -> None:
  172. self.close()
  173. @property
  174. def data(self) -> bytes:
  175. if self._body:
  176. return self._body
  177. else:
  178. return self.read(cache_content=True)
  179. def json(self) -> typing.Any:
  180. """
  181. Deserializes the body of the HTTP response as a Python object.
  182. The body of the HTTP response must be encoded using UTF-8, as per
  183. `RFC 8529 Section 8.1 <https://www.rfc-editor.org/rfc/rfc8259#section-8.1>`_.
  184. To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to
  185. your custom decoder instead.
  186. If the body of the HTTP response is not decodable to UTF-8, a
  187. `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a
  188. valid JSON document, a `json.JSONDecodeError` will be raised.
  189. Read more :ref:`here <json_content>`.
  190. :returns: The body of the HTTP response as a Python object.
  191. """
  192. data = self.data.decode("utf-8")
  193. return _json.loads(data)
  194. def close(self) -> None:
  195. if not self._closed:
  196. if isinstance(self._response.body, IOBase):
  197. self._response.body.close()
  198. if self._connection:
  199. self._connection.close()
  200. self._connection = None
  201. self._closed = True
  202. @contextmanager
  203. def _error_catcher(self) -> typing.Generator[None]:
  204. """
  205. Catch Emscripten specific exceptions thrown by fetch.py,
  206. instead re-raising urllib3 variants, so that low-level exceptions
  207. are not leaked in the high-level api.
  208. On exit, release the connection back to the pool.
  209. """
  210. from .fetch import _RequestError, _TimeoutError # avoid circular import
  211. clean_exit = False
  212. try:
  213. yield
  214. # If no exception is thrown, we should avoid cleaning up
  215. # unnecessarily.
  216. clean_exit = True
  217. except _TimeoutError as e:
  218. raise TimeoutError(str(e))
  219. except _RequestError as e:
  220. raise HTTPException(str(e))
  221. finally:
  222. # If we didn't terminate cleanly, we need to throw away our
  223. # connection.
  224. if not clean_exit:
  225. # The response may not be closed but we're not going to use it
  226. # anymore so close it now
  227. if (
  228. isinstance(self._response.body, IOBase)
  229. and not self._response.body.closed
  230. ):
  231. self._response.body.close()
  232. # release the connection back to the pool
  233. self.release_conn()
  234. else:
  235. # If we have read everything from the response stream,
  236. # return the connection back to the pool.
  237. if (
  238. isinstance(self._response.body, IOBase)
  239. and self._response.body.closed
  240. ):
  241. self.release_conn()