utils.py 4.1 KB

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