utils.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import asyncio
  2. import functools
  3. import inspect
  4. import queue
  5. import random
  6. import socket
  7. import string
  8. from collections import OrderedDict
  9. from contextlib import closing
  10. from os.path import abspath, dirname
  11. import time
  12. project_dir = dirname(abspath(__file__))
  13. STATIC_PATH = '%s/html' % project_dir
  14. def catch_exp_call(func, logger):
  15. """运行函数,将捕获异常记录到日志
  16. :param func: 函数
  17. :param logger: 日志
  18. :return: ``func`` 返回值
  19. """
  20. try:
  21. return func()
  22. except Exception:
  23. logger.exception("Error when invoke `%s`" % func)
  24. def iscoroutinefunction(object):
  25. while isinstance(object, functools.partial):
  26. object = object.func
  27. return asyncio.iscoroutinefunction(object)
  28. def isgeneratorfunction(object):
  29. while isinstance(object, functools.partial):
  30. object = object.func
  31. return inspect.isgeneratorfunction(object)
  32. def get_function_name(func, default=None):
  33. while isinstance(func, functools.partial):
  34. func = func.func
  35. return getattr(func, '__name__', default)
  36. class LimitedSizeQueue(queue.Queue):
  37. """
  38. 有限大小的队列
  39. `get()` 返回全部数据
  40. 队列满时,再 `put()` 会阻塞
  41. """
  42. def get(self):
  43. """获取队列全部数据"""
  44. try:
  45. return super().get(block=False)
  46. except queue.Empty:
  47. return []
  48. def wait_empty(self, timeout=None):
  49. """等待队列内的数据被取走"""
  50. with self.not_full:
  51. if self._qsize() == 0:
  52. return
  53. if timeout is None:
  54. self.not_full.wait()
  55. elif timeout < 0:
  56. raise ValueError("'timeout' must be a non-negative number")
  57. else:
  58. self.not_full.wait(timeout)
  59. def _init(self, maxsize):
  60. self.queue = []
  61. def _qsize(self):
  62. return len(self.queue)
  63. # Put a new item in the queue
  64. def _put(self, item):
  65. self.queue.append(item)
  66. # Get an item from the queue
  67. def _get(self):
  68. all_data = self.queue
  69. self.queue = []
  70. return all_data
  71. async def wait_host_port(host, port, duration=10, delay=2):
  72. """Repeatedly try if a port on a host is open until duration seconds passed
  73. from: https://gist.github.com/betrcode/0248f0fda894013382d7#gistcomment-3161499
  74. :param str host: host ip address or hostname
  75. :param int port: port number
  76. :param int/float duration: Optional. Total duration in seconds to wait, by default 10
  77. :param int/float delay: Optional. Delay in seconds between each try, by default 2
  78. :return: awaitable bool
  79. """
  80. tmax = time.time() + duration
  81. while time.time() < tmax:
  82. try:
  83. _reader, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout=5)
  84. writer.close()
  85. await writer.wait_closed()
  86. return True
  87. except Exception:
  88. if delay:
  89. await asyncio.sleep(delay)
  90. return False
  91. def get_free_port():
  92. """
  93. pick a free port number
  94. :return int: port number
  95. """
  96. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
  97. s.bind(('', 0))
  98. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  99. return s.getsockname()[1]
  100. def random_str(len=16):
  101. """生成小写字母和数组组成的随机字符串
  102. :param int len: 字符串长度
  103. """
  104. return ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(len))
  105. def run_as_function(gen):
  106. res = None
  107. while 1:
  108. try:
  109. res = gen.send(res)
  110. except StopIteration as e:
  111. if len(e.args) == 1:
  112. return e.args[0]
  113. return
  114. async def to_coroutine(gen):
  115. res = None
  116. while 1:
  117. try:
  118. c = gen.send(res)
  119. res = await c
  120. except StopIteration as e:
  121. if len(e.args) == 1:
  122. return e.args[0]
  123. return
  124. class LRUDict(OrderedDict):
  125. """
  126. Store items in the order the keys were last recent updated.
  127. The last recent updated item was in end.
  128. The last furthest updated item was in front.
  129. """
  130. def __setitem__(self, key, value):
  131. OrderedDict.__setitem__(self, key, value)
  132. self.move_to_end(key)