utils.py 3.8 KB

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