utils.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import asyncio
  2. import functools
  3. import inspect
  4. import os
  5. import queue
  6. import random
  7. import socket
  8. import string
  9. import time
  10. from collections import OrderedDict
  11. from contextlib import closing
  12. from os.path import abspath, dirname
  13. project_dir = dirname(abspath(__file__))
  14. STATIC_PATH = '%s/html' % project_dir
  15. class Setter:
  16. """
  17. 可以在对象属性上保存数据。
  18. 访问数据对象不存在的属性时会返回None而不是抛出异常。
  19. """
  20. def __getattribute__(self, name):
  21. try:
  22. return super().__getattribute__(name)
  23. except AttributeError:
  24. return None
  25. class ObjectDictProxy:
  26. """
  27. 通过属性访问的字典。实例不维护底层字典,而是每次在访问时使用回调函数获取
  28. 在对象属性上保存的数据会被保存到底层字典中
  29. 访问数据对象不存在的属性时会返回None而不是抛出异常。
  30. 不能保存下划线开始的属性
  31. 用 ``obj._dict`` 获取对象的字典表示
  32. Example::
  33. d = {}
  34. data = LazyObjectDict(lambda: d)
  35. data.name = "Wang"
  36. data.age = 22
  37. assert data.foo is None
  38. data[10] = "10"
  39. for key in data:
  40. print(key)
  41. assert 'bar' not in data
  42. assert 'name' in data
  43. assert data._dict is d
  44. print(data._dict)
  45. """
  46. def __init__(self, dict_getter):
  47. # 使用 self.__dict__ 避免触发 __setattr__
  48. self.__dict__['_dict_getter'] = dict_getter
  49. @property
  50. def _dict(self):
  51. return self._dict_getter()
  52. def __len__(self):
  53. return len(self._dict)
  54. def __getitem__(self, key):
  55. if key in self._dict:
  56. return self._dict[key]
  57. raise KeyError(key)
  58. def __setitem__(self, key, item):
  59. self._dict[key] = item
  60. def __delitem__(self, key):
  61. del self._dict[key]
  62. def __iter__(self):
  63. return iter(self._dict)
  64. def __contains__(self, key):
  65. return key in self._dict
  66. def __repr__(self):
  67. return repr(self._dict)
  68. def __setattr__(self, key, value):
  69. """
  70. 无论属性是否存在都会被调用
  71. 使用 self.__dict__[name] = value 避免递归
  72. """
  73. assert not key.startswith('_'), "Cannot set attributes starting with underscore"
  74. self._dict.__setitem__(key, value)
  75. def __getattr__(self, item):
  76. """访问一个不存在的属性时触发"""
  77. assert not item.startswith('_'), 'object has no attribute %s' % item
  78. return self._dict.get(item, None)
  79. def __delattr__(self, item):
  80. try:
  81. del self._dict[item]
  82. except KeyError:
  83. pass
  84. class ObjectDict(dict):
  85. """
  86. Object like dict, every dict[key] can visite by dict.key
  87. If dict[key] is `Get`, calculate it's value.
  88. """
  89. def __getattr__(self, name):
  90. ret = self.__getitem__(name)
  91. if hasattr(ret, '__get__'):
  92. return ret.__get__(self, ObjectDict)
  93. return ret
  94. def catch_exp_call(func, logger):
  95. """运行函数,将捕获异常记录到日志
  96. :param func: 函数
  97. :param logger: 日志
  98. :return: ``func`` 返回值
  99. """
  100. try:
  101. return func()
  102. except Exception:
  103. logger.exception("Error when invoke `%s`" % func)
  104. def iscoroutinefunction(object):
  105. while isinstance(object, functools.partial):
  106. object = object.func
  107. return asyncio.iscoroutinefunction(object)
  108. def isgeneratorfunction(object):
  109. while isinstance(object, functools.partial):
  110. object = object.func
  111. return inspect.isgeneratorfunction(object)
  112. def get_function_name(func, default=None):
  113. while isinstance(func, functools.partial):
  114. func = func.func
  115. return getattr(func, '__name__', default)
  116. def get_function_doc(func):
  117. """获取函数的doc注释
  118. 如果函数被functools.partial包装,则返回内部原始函数的文档,可以通过设置新函数的 func.__doc__ 属性来更新doc注释
  119. """
  120. partial_doc = inspect.getdoc(functools.partial)
  121. if isinstance(func, functools.partial) and getattr(func, '__doc__', '') == partial_doc:
  122. while isinstance(func, functools.partial):
  123. func = func.func
  124. return inspect.getdoc(func) or ''
  125. def get_function_seo_info(func):
  126. """获取使用 pywebio.platform.utils.seo() 设置在函数上的SEO信息
  127. """
  128. if hasattr(func, '_pywebio_title'):
  129. return func._pywebio_title, func._pywebio_description
  130. while isinstance(func, functools.partial):
  131. func = func.func
  132. if hasattr(func, '_pywebio_title'):
  133. return func._pywebio_title, func._pywebio_description
  134. return None
  135. class LimitedSizeQueue(queue.Queue):
  136. """
  137. 有限大小的队列
  138. `get()` 返回全部数据
  139. 队列满时,再 `put()` 会阻塞
  140. """
  141. def get(self):
  142. """获取队列全部数据"""
  143. try:
  144. return super().get(block=False)
  145. except queue.Empty:
  146. return []
  147. def wait_empty(self, timeout=None):
  148. """等待队列内的数据被取走"""
  149. with self.not_full:
  150. if self._qsize() == 0:
  151. return
  152. if timeout is None:
  153. self.not_full.wait()
  154. elif timeout < 0:
  155. raise ValueError("'timeout' must be a non-negative number")
  156. else:
  157. self.not_full.wait(timeout)
  158. def _init(self, maxsize):
  159. self.queue = []
  160. def _qsize(self):
  161. return len(self.queue)
  162. # Put a new item in the queue
  163. def _put(self, item):
  164. self.queue.append(item)
  165. # Get an item from the queue
  166. def _get(self):
  167. all_data = self.queue
  168. self.queue = []
  169. return all_data
  170. async def wait_host_port(host, port, duration=10, delay=2):
  171. """Repeatedly try if a port on a host is open until duration seconds passed
  172. from: https://gist.github.com/betrcode/0248f0fda894013382d7#gistcomment-3161499
  173. :param str host: host ip address or hostname
  174. :param int port: port number
  175. :param int/float duration: Optional. Total duration in seconds to wait, by default 10
  176. :param int/float delay: Optional. Delay in seconds between each try, by default 2
  177. :return: awaitable bool
  178. """
  179. tmax = time.time() + duration
  180. while time.time() < tmax:
  181. try:
  182. _, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout=5)
  183. writer.close()
  184. # asyncio.StreamWriter.wait_closed is introduced in py 3.7
  185. # See https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamWriter.wait_closed
  186. if hasattr(writer, 'wait_closed'):
  187. await writer.wait_closed()
  188. return True
  189. except Exception:
  190. if delay:
  191. await asyncio.sleep(delay)
  192. return False
  193. def get_free_port():
  194. """
  195. pick a free port number
  196. :return int: port number
  197. """
  198. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
  199. s.bind(('', 0))
  200. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  201. return s.getsockname()[1]
  202. def random_str(length=16):
  203. """生成字母和数组组成的随机字符串
  204. :param int length: 字符串长度
  205. """
  206. candidates = string.ascii_letters + string.digits
  207. return ''.join(random.SystemRandom().choice(candidates) for _ in range(length))
  208. def run_as_function(gen):
  209. res = None
  210. while 1:
  211. try:
  212. res = gen.send(res)
  213. except StopIteration as e:
  214. if len(e.args) == 1:
  215. return e.args[0]
  216. return
  217. async def to_coroutine(gen):
  218. res = None
  219. while 1:
  220. try:
  221. c = gen.send(res)
  222. res = await c
  223. except StopIteration as e:
  224. if len(e.args) == 1:
  225. return e.args[0]
  226. return
  227. class LRUDict(OrderedDict):
  228. """
  229. Store items in the order the keys were last recent updated.
  230. The last recent updated item was in end.
  231. The last furthest updated item was in front.
  232. """
  233. def __setitem__(self, key, value):
  234. OrderedDict.__setitem__(self, key, value)
  235. self.move_to_end(key)
  236. _html_value_chars = set(string.ascii_letters + string.digits + '_-')
  237. def is_html_safe_value(val):
  238. """检查是字符串是否可以作为html属性值"""
  239. return all(i in _html_value_chars for i in val)
  240. def check_webio_js():
  241. js_files = [os.path.join(STATIC_PATH, 'js', i) for i in ('pywebio.js', 'pywebio.min.js')]
  242. if any(os.path.isfile(f) for f in js_files):
  243. return
  244. error_msg = """
  245. Error: Missing pywebio.js library for frontend page.
  246. This may be because you cloned or downloaded the project directly from the Git repository.
  247. You Can:
  248. * Manually build the pywebio.js file. See `webiojs/README.md` for more info.
  249. OR
  250. * Use the following command to install the latest development version of PyWebIO:
  251. pip3 install -U https://code.aliyun.com/wang0618/pywebio/repository/archive.zip
  252. """.strip()
  253. raise RuntimeError(error_msg)