__init__.py 7.0 KB

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