25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

94 lines
2.1 KiB

  1. """Various base classes."""
  2. import asyncio
  3. from collections.abc import Coroutine
  4. class AsyncBase:
  5. def __init__(self, file, loop, executor):
  6. self._file = file
  7. self._loop = loop
  8. self._executor = executor
  9. def __aiter__(self):
  10. """We are our own iterator."""
  11. return self
  12. @asyncio.coroutine
  13. def __anext__(self):
  14. """Simulate normal file iteration."""
  15. line = yield from self.readline()
  16. if line:
  17. return line
  18. else:
  19. raise StopAsyncIteration
  20. class _ContextManager(Coroutine):
  21. __slots__ = ('_coro', '_obj')
  22. def __init__(self, coro):
  23. self._coro = coro
  24. self._obj = None
  25. def send(self, value):
  26. return self._coro.send(value)
  27. def throw(self, typ, val=None, tb=None):
  28. if val is None:
  29. return self._coro.throw(typ)
  30. elif tb is None:
  31. return self._coro.throw(typ, val)
  32. else:
  33. return self._coro.throw(typ, val, tb)
  34. def close(self):
  35. return self._coro.close()
  36. @property
  37. def gi_frame(self):
  38. return self._coro.gi_frame
  39. @property
  40. def gi_running(self):
  41. return self._coro.gi_running
  42. @property
  43. def gi_code(self):
  44. return self._coro.gi_code
  45. def __next__(self):
  46. return self.send(None)
  47. @asyncio.coroutine
  48. def __iter__(self):
  49. resp = yield from self._coro
  50. return resp
  51. def __await__(self):
  52. resp = yield from self._coro
  53. return resp
  54. @asyncio.coroutine
  55. def __anext__(self):
  56. resp = yield from self._coro
  57. return resp
  58. @asyncio.coroutine
  59. def __aenter__(self):
  60. self._obj = yield from self._coro
  61. return self._obj
  62. @asyncio.coroutine
  63. def __aexit__(self, exc_type, exc, tb):
  64. self._obj.close()
  65. self._obj = None
  66. class AiofilesContextManager(_ContextManager):
  67. """An adjusted async context manager for aiofiles."""
  68. @asyncio.coroutine
  69. def __aexit__(self, exc_type, exc_val, exc_tb):
  70. yield from self._obj.close()
  71. self._obj = None