__init__.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring, global-statement
  3. import asyncio
  4. import threading
  5. import concurrent.futures
  6. from queue import SimpleQueue
  7. from types import MethodType
  8. from timeit import default_timer
  9. from typing import Iterable, NamedTuple, Tuple, List, Dict, Union
  10. from contextlib import contextmanager
  11. import httpx
  12. import anyio
  13. from .network import get_network, initialize, check_network_configuration # pylint:disable=cyclic-import
  14. from .client import get_loop
  15. from .raise_for_httperror import raise_for_httperror
  16. THREADLOCAL = threading.local()
  17. """Thread-local data is data for thread specific values."""
  18. def reset_time_for_thread():
  19. THREADLOCAL.total_time = 0
  20. def get_time_for_thread():
  21. """returns thread's total time or None"""
  22. return THREADLOCAL.__dict__.get('total_time')
  23. def set_timeout_for_thread(timeout, start_time=None):
  24. THREADLOCAL.timeout = timeout
  25. THREADLOCAL.start_time = start_time
  26. def set_context_network_name(network_name):
  27. THREADLOCAL.network = get_network(network_name)
  28. def get_context_network():
  29. """If set return thread's network.
  30. If unset, return value from :py:obj:`get_network`.
  31. """
  32. return THREADLOCAL.__dict__.get('network') or get_network()
  33. @contextmanager
  34. def _record_http_time():
  35. # pylint: disable=too-many-branches
  36. time_before_request = default_timer()
  37. start_time = getattr(THREADLOCAL, 'start_time', time_before_request)
  38. try:
  39. yield start_time
  40. finally:
  41. # update total_time.
  42. # See get_time_for_thread() and reset_time_for_thread()
  43. if hasattr(THREADLOCAL, 'total_time'):
  44. time_after_request = default_timer()
  45. THREADLOCAL.total_time += time_after_request - time_before_request
  46. def _get_timeout(start_time, kwargs):
  47. # pylint: disable=too-many-branches
  48. # timeout (httpx)
  49. if 'timeout' in kwargs:
  50. timeout = kwargs['timeout']
  51. else:
  52. timeout = getattr(THREADLOCAL, 'timeout', None)
  53. if timeout is not None:
  54. kwargs['timeout'] = timeout
  55. # 2 minutes timeout for the requests without timeout
  56. timeout = timeout or 120
  57. # adjust actual timeout
  58. timeout += 0.2 # overhead
  59. if start_time:
  60. timeout -= default_timer() - start_time
  61. return timeout
  62. def request(method, url, **kwargs):
  63. """same as requests/requests/api.py request(...)"""
  64. with _record_http_time() as start_time:
  65. network = get_context_network()
  66. timeout = _get_timeout(start_time, kwargs)
  67. future = asyncio.run_coroutine_threadsafe(network.request(method, url, **kwargs), get_loop())
  68. try:
  69. return future.result(timeout)
  70. except concurrent.futures.TimeoutError as e:
  71. raise httpx.TimeoutException('Timeout', request=None) from e
  72. def multi_requests(request_list: List["Request"]) -> List[Union[httpx.Response, Exception]]:
  73. """send multiple HTTP requests in parallel. Wait for all requests to finish."""
  74. with _record_http_time() as start_time:
  75. # send the requests
  76. network = get_context_network()
  77. loop = get_loop()
  78. future_list = []
  79. for request_desc in request_list:
  80. timeout = _get_timeout(start_time, request_desc.kwargs)
  81. future = asyncio.run_coroutine_threadsafe(
  82. network.request(request_desc.method, request_desc.url, **request_desc.kwargs), loop
  83. )
  84. future_list.append((future, timeout))
  85. # read the responses
  86. responses = []
  87. for future, timeout in future_list:
  88. try:
  89. responses.append(future.result(timeout))
  90. except concurrent.futures.TimeoutError:
  91. responses.append(httpx.TimeoutException('Timeout', request=None))
  92. except Exception as e: # pylint: disable=broad-except
  93. responses.append(e)
  94. return responses
  95. class Request(NamedTuple):
  96. """Request description for the multi_requests function"""
  97. method: str
  98. url: str
  99. kwargs: Dict[str, str] = {}
  100. @staticmethod
  101. def get(url, **kwargs):
  102. return Request('GET', url, kwargs)
  103. @staticmethod
  104. def options(url, **kwargs):
  105. return Request('OPTIONS', url, kwargs)
  106. @staticmethod
  107. def head(url, **kwargs):
  108. return Request('HEAD', url, kwargs)
  109. @staticmethod
  110. def post(url, **kwargs):
  111. return Request('POST', url, kwargs)
  112. @staticmethod
  113. def put(url, **kwargs):
  114. return Request('PUT', url, kwargs)
  115. @staticmethod
  116. def patch(url, **kwargs):
  117. return Request('PATCH', url, kwargs)
  118. @staticmethod
  119. def delete(url, **kwargs):
  120. return Request('DELETE', url, kwargs)
  121. def get(url, **kwargs):
  122. kwargs.setdefault('allow_redirects', True)
  123. return request('get', url, **kwargs)
  124. def options(url, **kwargs):
  125. kwargs.setdefault('allow_redirects', True)
  126. return request('options', url, **kwargs)
  127. def head(url, **kwargs):
  128. kwargs.setdefault('allow_redirects', False)
  129. return request('head', url, **kwargs)
  130. def post(url, data=None, **kwargs):
  131. return request('post', url, data=data, **kwargs)
  132. def put(url, data=None, **kwargs):
  133. return request('put', url, data=data, **kwargs)
  134. def patch(url, data=None, **kwargs):
  135. return request('patch', url, data=data, **kwargs)
  136. def delete(url, **kwargs):
  137. return request('delete', url, **kwargs)
  138. async def stream_chunk_to_queue(network, queue, method, url, **kwargs):
  139. try:
  140. async with await network.stream(method, url, **kwargs) as response:
  141. queue.put(response)
  142. # aiter_raw: access the raw bytes on the response without applying any HTTP content decoding
  143. # https://www.python-httpx.org/quickstart/#streaming-responses
  144. async for chunk in response.aiter_raw(65536):
  145. if len(chunk) > 0:
  146. queue.put(chunk)
  147. except (httpx.StreamClosed, anyio.ClosedResourceError):
  148. # the response was queued before the exception.
  149. # the exception was raised on aiter_raw.
  150. # we do nothing here: in the finally block, None will be queued
  151. # so stream(method, url, **kwargs) generator can stop
  152. pass
  153. except Exception as e: # pylint: disable=broad-except
  154. # broad except to avoid this scenario:
  155. # exception in network.stream(method, url, **kwargs)
  156. # -> the exception is not catch here
  157. # -> queue None (in finally)
  158. # -> the function below steam(method, url, **kwargs) has nothing to return
  159. queue.put(e)
  160. finally:
  161. queue.put(None)
  162. def _stream_generator(method, url, **kwargs):
  163. queue = SimpleQueue()
  164. network = get_context_network()
  165. future = asyncio.run_coroutine_threadsafe(stream_chunk_to_queue(network, queue, method, url, **kwargs), get_loop())
  166. # yield chunks
  167. obj_or_exception = queue.get()
  168. while obj_or_exception is not None:
  169. if isinstance(obj_or_exception, Exception):
  170. raise obj_or_exception
  171. yield obj_or_exception
  172. obj_or_exception = queue.get()
  173. future.result()
  174. def _close_response_method(self):
  175. asyncio.run_coroutine_threadsafe(self.aclose(), get_loop())
  176. # reach the end of _self.generator ( _stream_generator ) to an avoid memory leak.
  177. # it makes sure that :
  178. # * the httpx response is closed (see the stream_chunk_to_queue function)
  179. # * to call future.result() in _stream_generator
  180. for _ in self._generator: # pylint: disable=protected-access
  181. continue
  182. def stream(method, url, **kwargs) -> Tuple[httpx.Response, Iterable[bytes]]:
  183. """Replace httpx.stream.
  184. Usage:
  185. response, stream = poolrequests.stream(...)
  186. for chunk in stream:
  187. ...
  188. httpx.Client.stream requires to write the httpx.HTTPTransport version of the
  189. the httpx.AsyncHTTPTransport declared above.
  190. """
  191. generator = _stream_generator(method, url, **kwargs)
  192. # yield response
  193. response = next(generator) # pylint: disable=stop-iteration-return
  194. if isinstance(response, Exception):
  195. raise response
  196. response._generator = generator # pylint: disable=protected-access
  197. response.close = MethodType(_close_response_method, response)
  198. return response, generator