__init__.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. import asyncio
  3. import threading
  4. import concurrent.futures
  5. from timeit import default_timer
  6. import httpx
  7. import h2.exceptions
  8. from .network import get_network, initialize
  9. from .client import get_loop
  10. from .raise_for_httperror import raise_for_httperror
  11. # queue.SimpleQueue: Support Python 3.6
  12. try:
  13. from queue import SimpleQueue
  14. except ImportError:
  15. from queue import Empty
  16. from collections import deque
  17. class SimpleQueue:
  18. """Minimal backport of queue.SimpleQueue"""
  19. def __init__(self):
  20. self._queue = deque()
  21. self._count = threading.Semaphore(0)
  22. def put(self, item):
  23. self._queue.append(item)
  24. self._count.release()
  25. def get(self):
  26. if not self._count.acquire(True):
  27. raise Empty
  28. return self._queue.popleft()
  29. THREADLOCAL = threading.local()
  30. def reset_time_for_thread():
  31. THREADLOCAL.total_time = 0
  32. def get_time_for_thread():
  33. """returns thread's total time or None"""
  34. return THREADLOCAL.__dict__.get('total_time')
  35. def set_timeout_for_thread(timeout, start_time=None):
  36. THREADLOCAL.timeout = timeout
  37. THREADLOCAL.start_time = start_time
  38. def set_context_network_name(network_name):
  39. THREADLOCAL.network = get_network(network_name)
  40. def get_context_network():
  41. """If set return thread's network.
  42. If unset, return value from :py:obj:`get_network`.
  43. """
  44. return THREADLOCAL.__dict__.get('network') or get_network()
  45. def request(method, url, **kwargs):
  46. """same as requests/requests/api.py request(...)"""
  47. time_before_request = default_timer()
  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. # ajdust actual timeout
  58. timeout += 0.2 # overhead
  59. start_time = getattr(THREADLOCAL, 'start_time', time_before_request)
  60. if start_time:
  61. timeout -= default_timer() - start_time
  62. # raise_for_error
  63. check_for_httperror = True
  64. if 'raise_for_httperror' in kwargs:
  65. check_for_httperror = kwargs['raise_for_httperror']
  66. del kwargs['raise_for_httperror']
  67. # requests compatibility
  68. if isinstance(url, bytes):
  69. url = url.decode()
  70. # network
  71. network = get_context_network()
  72. # do request
  73. future = asyncio.run_coroutine_threadsafe(network.request(method, url, **kwargs), get_loop())
  74. try:
  75. response = future.result(timeout)
  76. except concurrent.futures.TimeoutError as e:
  77. raise httpx.TimeoutException('Timeout', request=None) from e
  78. # requests compatibility
  79. # see also https://www.python-httpx.org/compatibility/#checking-for-4xx5xx-responses
  80. response.ok = not response.is_error
  81. # update total_time.
  82. # See get_time_for_thread() and reset_time_for_thread()
  83. if hasattr(THREADLOCAL, 'total_time'):
  84. time_after_request = default_timer()
  85. THREADLOCAL.total_time += time_after_request - time_before_request
  86. # raise an exception
  87. if check_for_httperror:
  88. raise_for_httperror(response)
  89. return response
  90. def get(url, **kwargs):
  91. kwargs.setdefault('allow_redirects', True)
  92. return request('get', url, **kwargs)
  93. def options(url, **kwargs):
  94. kwargs.setdefault('allow_redirects', True)
  95. return request('options', url, **kwargs)
  96. def head(url, **kwargs):
  97. kwargs.setdefault('allow_redirects', False)
  98. return request('head', url, **kwargs)
  99. def post(url, data=None, **kwargs):
  100. return request('post', url, data=data, **kwargs)
  101. def put(url, data=None, **kwargs):
  102. return request('put', url, data=data, **kwargs)
  103. def patch(url, data=None, **kwargs):
  104. return request('patch', url, data=data, **kwargs)
  105. def delete(url, **kwargs):
  106. return request('delete', url, **kwargs)
  107. async def stream_chunk_to_queue(network, q, method, url, **kwargs):
  108. try:
  109. async with network.stream(method, url, **kwargs) as response:
  110. q.put(response)
  111. async for chunk in response.aiter_bytes(65536):
  112. if len(chunk) > 0:
  113. q.put(chunk)
  114. except (httpx.HTTPError, OSError, h2.exceptions.ProtocolError) as e:
  115. q.put(e)
  116. finally:
  117. q.put(None)
  118. def stream(method, url, **kwargs):
  119. """Replace httpx.stream.
  120. Usage:
  121. stream = poolrequests.stream(...)
  122. response = next(stream)
  123. for chunk in stream:
  124. ...
  125. httpx.Client.stream requires to write the httpx.HTTPTransport version of the
  126. the httpx.AsyncHTTPTransport declared above.
  127. """
  128. q = SimpleQueue()
  129. future = asyncio.run_coroutine_threadsafe(stream_chunk_to_queue(get_network(), q, method, url, **kwargs),
  130. get_loop())
  131. chunk_or_exception = q.get()
  132. while chunk_or_exception is not None:
  133. if isinstance(chunk_or_exception, Exception):
  134. raise chunk_or_exception
  135. yield chunk_or_exception
  136. chunk_or_exception = q.get()
  137. return future.result()