1
0

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 ReadOnlyObjectDict(ObjectDictProxy):
  85. def __delitem__(self, key):
  86. raise NotImplementedError
  87. def __delattr__(self, item):
  88. raise NotImplementedError
  89. def __setitem__(self, key, item):
  90. raise NotImplementedError
  91. def __setattr__(self, key, value):
  92. raise NotImplementedError
  93. def catch_exp_call(func, logger):
  94. """运行函数,将捕获异常记录到日志
  95. :param func: 函数
  96. :param logger: 日志
  97. :return: ``func`` 返回值
  98. """
  99. try:
  100. return func()
  101. except Exception:
  102. logger.exception("Error when invoke `%s`" % func)
  103. def iscoroutinefunction(object):
  104. while isinstance(object, functools.partial):
  105. object = object.func
  106. return asyncio.iscoroutinefunction(object)
  107. def isgeneratorfunction(object):
  108. while isinstance(object, functools.partial):
  109. object = object.func
  110. return inspect.isgeneratorfunction(object)
  111. def get_function_name(func, default=None):
  112. while isinstance(func, functools.partial):
  113. func = func.func
  114. return getattr(func, '__name__', default)
  115. def get_function_doc(func):
  116. """获取函数的doc注释
  117. 如果函数被functools.partial包装,则返回内部原始函数的文档,可以通过设置新函数的 func.__doc__ 属性来更新doc注释
  118. """
  119. partial_doc = inspect.getdoc(functools.partial)
  120. if isinstance(func, functools.partial) and getattr(func, '__doc__', '') == partial_doc:
  121. while isinstance(func, functools.partial):
  122. func = func.func
  123. return inspect.getdoc(func) or ''
  124. def get_function_seo_info(func):
  125. """获取使用 pywebio.platform.utils.seo() 设置在函数上的SEO信息
  126. """
  127. if hasattr(func, '_pywebio_title'):
  128. return func._pywebio_title, func._pywebio_description
  129. while isinstance(func, functools.partial):
  130. func = func.func
  131. if hasattr(func, '_pywebio_title'):
  132. return func._pywebio_title, func._pywebio_description
  133. return None
  134. class LimitedSizeQueue(queue.Queue):
  135. """
  136. 有限大小的队列
  137. `get()` 返回全部数据
  138. 队列满时,再 `put()` 会阻塞
  139. """
  140. def get(self):
  141. """获取队列全部数据"""
  142. try:
  143. return super().get(block=False)
  144. except queue.Empty:
  145. return []
  146. def wait_empty(self, timeout=None):
  147. """等待队列内的数据被取走"""
  148. with self.not_full:
  149. if self._qsize() == 0:
  150. return
  151. if timeout is None:
  152. self.not_full.wait()
  153. elif timeout < 0:
  154. raise ValueError("'timeout' must be a non-negative number")
  155. else:
  156. self.not_full.wait(timeout)
  157. def _init(self, maxsize):
  158. self.queue = []
  159. def _qsize(self):
  160. return len(self.queue)
  161. # Put a new item in the queue
  162. def _put(self, item):
  163. self.queue.append(item)
  164. # Get an item from the queue
  165. def _get(self):
  166. all_data = self.queue
  167. self.queue = []
  168. return all_data
  169. async def wait_host_port(host, port, duration=10, delay=2):
  170. """Repeatedly try if a port on a host is open until duration seconds passed
  171. from: https://gist.github.com/betrcode/0248f0fda894013382d7#gistcomment-3161499
  172. :param str host: host ip address or hostname
  173. :param int port: port number
  174. :param int/float duration: Optional. Total duration in seconds to wait, by default 10
  175. :param int/float delay: Optional. Delay in seconds between each try, by default 2
  176. :return: awaitable bool
  177. """
  178. tmax = time.time() + duration
  179. while time.time() < tmax:
  180. try:
  181. _, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout=5)
  182. writer.close()
  183. # asyncio.StreamWriter.wait_closed is introduced in py 3.7
  184. # See https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamWriter.wait_closed
  185. if hasattr(writer, 'wait_closed'):
  186. await writer.wait_closed()
  187. return True
  188. except Exception:
  189. if delay:
  190. await asyncio.sleep(delay)
  191. return False
  192. def get_free_port():
  193. """
  194. pick a free port number
  195. :return int: port number
  196. """
  197. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
  198. s.bind(('', 0))
  199. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  200. return s.getsockname()[1]
  201. def random_str(length=16):
  202. """生成字母和数组组成的随机字符串
  203. :param int length: 字符串长度
  204. """
  205. candidates = string.ascii_letters + string.digits
  206. return ''.join(random.SystemRandom().choice(candidates) for _ in range(length))
  207. def run_as_function(gen):
  208. res = None
  209. while 1:
  210. try:
  211. res = gen.send(res)
  212. except StopIteration as e:
  213. if len(e.args) == 1:
  214. return e.args[0]
  215. return
  216. async def to_coroutine(gen):
  217. res = None
  218. while 1:
  219. try:
  220. c = gen.send(res)
  221. res = await c
  222. except StopIteration as e:
  223. if len(e.args) == 1:
  224. return e.args[0]
  225. return
  226. class LRUDict(OrderedDict):
  227. """
  228. Store items in the order the keys were last recent updated.
  229. The last recent updated item was in end.
  230. The last furthest updated item was in front.
  231. """
  232. def __setitem__(self, key, value):
  233. OrderedDict.__setitem__(self, key, value)
  234. self.move_to_end(key)
  235. _html_value_chars = set(string.ascii_letters + string.digits + '_-')
  236. def is_html_safe_value(val):
  237. """检查是字符串是否可以作为html属性值"""
  238. return all(i in _html_value_chars for i in val)
  239. def check_webio_js():
  240. js_files = [os.path.join(STATIC_PATH, 'js', i) for i in ('pywebio.js', 'pywebio.min.js')]
  241. if any(os.path.isfile(f) for f in js_files):
  242. return
  243. error_msg = """
  244. Error: Missing pywebio.js library for frontend page.
  245. This may be because you cloned or downloaded the project directly from the Git repository.
  246. You Can:
  247. * Manually build the pywebio.js file. See `webiojs/README.md` for more info.
  248. OR
  249. * Use the following command to install the latest development version of PyWebIO:
  250. pip3 install -U https://code.aliyun.com/wang0618/pywebio/repository/archive.zip
  251. """.strip()
  252. raise RuntimeError(error_msg)