PageRenderTime 26ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/venv/Lib/site-packages/async_timeout/__init__.py

https://bitbucket.org/inbar_donag_/advisor-pro-server-test
Python | 97 lines | 87 code | 4 blank | 6 comment | 0 complexity | d2a7fea1130d67f3f09d12ff63d96f13 MD5 | raw file
  1. import asyncio
  2. __version__ = '2.0.0'
  3. class timeout:
  4. """timeout context manager.
  5. Useful in cases when you want to apply timeout logic around block
  6. of code or in cases when asyncio.wait_for is not suitable. For example:
  7. >>> with timeout(0.001):
  8. ... async with aiohttp.get('https://github.com') as r:
  9. ... await r.text()
  10. timeout - value in seconds or None to disable timeout logic
  11. loop - asyncio compatible event loop
  12. """
  13. def __init__(self, timeout, *, loop=None):
  14. self._timeout = timeout
  15. if loop is None:
  16. loop = asyncio.get_event_loop()
  17. self._loop = loop
  18. self._task = None
  19. self._cancelled = False
  20. self._cancel_handler = None
  21. self._cancel_at = None
  22. def __enter__(self):
  23. return self._do_enter()
  24. def __exit__(self, exc_type, exc_val, exc_tb):
  25. self._do_exit(exc_type)
  26. @asyncio.coroutine
  27. def __aenter__(self):
  28. return self._do_enter()
  29. @asyncio.coroutine
  30. def __aexit__(self, exc_type, exc_val, exc_tb):
  31. self._do_exit(exc_type)
  32. @property
  33. def expired(self):
  34. return self._cancelled
  35. @property
  36. def remaining(self):
  37. if self._cancel_at is not None:
  38. return max(self._cancel_at - self._loop.time(), 0.0)
  39. else:
  40. return None
  41. def _do_enter(self):
  42. # Support Tornado 5- without timeout
  43. # Details: https://github.com/python/asyncio/issues/392
  44. if self._timeout is None:
  45. return self
  46. self._task = current_task(self._loop)
  47. if self._task is None:
  48. raise RuntimeError('Timeout context manager should be used '
  49. 'inside a task')
  50. if self._timeout <= 0:
  51. self._loop.call_soon(self._cancel_task)
  52. return self
  53. self._cancel_at = self._loop.time() + self._timeout
  54. self._cancel_handler = self._loop.call_at(
  55. self._cancel_at, self._cancel_task)
  56. return self
  57. def _do_exit(self, exc_type):
  58. if exc_type is asyncio.CancelledError and self._cancelled:
  59. self._cancel_handler = None
  60. self._task = None
  61. raise asyncio.TimeoutError
  62. if self._timeout is not None and self._cancel_handler is not None:
  63. self._cancel_handler.cancel()
  64. self._cancel_handler = None
  65. self._task = None
  66. def _cancel_task(self):
  67. self._task.cancel()
  68. self._cancelled = True
  69. def current_task(loop):
  70. task = asyncio.Task.current_task(loop=loop)
  71. if task is None:
  72. if hasattr(loop, 'current_task'):
  73. task = loop.current_task()
  74. return task