utils.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import fnmatch
  2. import json
  3. import urllib.parse
  4. from collections import defaultdict
  5. from collections import namedtuple
  6. from collections.abc import Mapping, Sequence
  7. from functools import partial
  8. from os import path, environ
  9. from tornado import template
  10. from ..__version__ import __version__ as version
  11. from ..exceptions import PyWebIOWarning
  12. from ..utils import isgeneratorfunction, iscoroutinefunction, get_function_name, get_function_doc, \
  13. get_function_seo_info
  14. """
  15. The maximum size in bytes of a http request body or a websocket message, after which the request or websocket is aborted
  16. Set by `start_server()` or `path_deploy()`
  17. Used in `file_upload()` as the `max_size`/`max_total_size` parameter default or to validate the parameter.
  18. """
  19. MAX_PAYLOAD_SIZE = 0
  20. DEFAULT_CDN = "https://cdn.jsdelivr.net/gh/wang0618/PyWebIO-assets@v{version}/"
  21. BOOTSTRAP_VERSION = '4.4.1'
  22. AppMeta = namedtuple('App', 'title description')
  23. _here_dir = path.dirname(path.abspath(__file__))
  24. _index_page_tpl = template.Template(open(path.join(_here_dir, 'tpl', 'index.html'), encoding='utf8').read())
  25. def render_page(app, protocol, cdn):
  26. """渲染前端页面的HTML框架, 支持SEO
  27. :param callable app: PyWebIO app
  28. :param str protocol: 'ws'/'http'
  29. :param bool/str cdn: Whether to use CDN, also accept string as custom CDN URL
  30. :return: bytes content of rendered page
  31. """
  32. assert protocol in ('ws', 'http')
  33. meta = parse_app_metadata(app)
  34. if cdn is True:
  35. cdn = DEFAULT_CDN.format(version=version)
  36. elif not cdn:
  37. cdn = ''
  38. else: # user custom cdn
  39. cdn = cdn.rstrip('/') + '/'
  40. bootstrap_css = bootstrap_css_url()
  41. return _index_page_tpl.generate(title=meta.title or 'PyWebIO Application',
  42. description=meta.description, protocol=protocol,
  43. script=True, content='', base_url=cdn, bootstrap_css=bootstrap_css)
  44. def bootstrap_css_url():
  45. """Get bootstrap theme css url from environment variable PYWEBIO_THEME
  46. PYWEBIO_THEME can be one of bootswatch themes, or a custom css url.
  47. """
  48. theme_name = environ.get('PYWEBIO_THEME')
  49. bootswatch_themes = {'flatly', 'yeti', 'cerulean', 'pulse', 'journal', 'cosmo', 'sandstone', 'simplex', 'minty',
  50. 'slate', 'superhero', 'lumen', 'spacelab', 'materia', 'litera', 'sketchy', 'cyborg', 'solar',
  51. 'lux', 'united', 'darkly'}
  52. if theme_name in bootswatch_themes:
  53. return 'https://cdn.jsdelivr.net/npm/bootswatch@{version}/dist/{theme}/bootstrap.min.css'.format(
  54. version=BOOTSTRAP_VERSION, theme=theme_name)
  55. return theme_name # it's a url
  56. def cdn_validation(cdn, level='warn', stacklevel=3):
  57. """CDN availability check
  58. :param bool/str cdn: cdn parameter
  59. :param level: warn or error
  60. """
  61. assert level in ('warn', 'error')
  62. if cdn is True and 'dev' in version:
  63. if level == 'warn':
  64. import warnings
  65. warnings.warn("Default CDN is not supported in dev version. Ignore the CDN setting", PyWebIOWarning,
  66. stacklevel=stacklevel)
  67. return False
  68. else:
  69. raise ValueError("Default CDN is not supported in dev version. Please host static files by yourself.")
  70. return cdn
  71. def parse_app_metadata(func):
  72. """解析pywebio app元数据"""
  73. seo_info = get_function_seo_info(func)
  74. if seo_info:
  75. return AppMeta(*seo_info)
  76. doc = get_function_doc(func)
  77. parts = doc.strip().split('\n\n', 1)
  78. if len(parts) == 2:
  79. title, description = parts
  80. else:
  81. title, description = parts[0], ''
  82. return AppMeta(title, description)
  83. _app_list_tpl = template.Template("""
  84. <h1>Applications index</h1>
  85. <ul>
  86. {% for name,meta in apps_info.items() %}
  87. <li>
  88. {% if other_arguments is not None %}
  89. <a href="?app={{name}}{{other_arguments}}">{{ meta.title or name }}</a>:
  90. {% else %}
  91. <a href="javascript:WebIO.openApp('{{ name }}', true)">{{ meta.title or name }}</a>:
  92. {% end %}
  93. {% if meta.description %}
  94. {{ meta.description }}
  95. {% else %}
  96. <i>No description.</i>
  97. {% end %}
  98. </li>
  99. {% end %}
  100. </ul>
  101. """.strip())
  102. def get_static_index_content(apps, query_arguments=None):
  103. """生成默认的静态主页
  104. :param callable apps: PyWebIO apps
  105. :param str query_arguments: Url Query Arguments。为None时,表示使用WebIO.openApp跳转
  106. :return: bytes
  107. """
  108. apps_info = {
  109. name: parse_app_metadata(func)
  110. for name, func in apps.items()
  111. }
  112. qs = urllib.parse.parse_qs(query_arguments)
  113. qs.pop('app', None)
  114. other_arguments = urllib.parse.urlencode(qs, doseq=True)
  115. if other_arguments:
  116. other_arguments = '&' + other_arguments
  117. else:
  118. other_arguments = None
  119. content = _app_list_tpl.generate(apps_info=apps_info, other_arguments=other_arguments).decode('utf8')
  120. return content
  121. def _generate_default_index_app(apps):
  122. """默认的主页任务函数"""
  123. content = get_static_index_content(apps)
  124. def index():
  125. from pywebio.output import put_html
  126. put_html(content)
  127. return index
  128. def make_applications(applications):
  129. """格式化 applications 为 任务名->任务函数 的映射, 并提供默认主页
  130. :param applications: 接受 单一任务函数、字典、列表 类型
  131. :return dict: 任务名->任务函数 的映射
  132. """
  133. if isinstance(applications, Sequence): # 列表 类型
  134. applications, app_list = {}, applications
  135. for func in app_list:
  136. name = get_function_name(func)
  137. if name in applications:
  138. raise ValueError("Duplicated application name:%r" % name)
  139. applications[name] = func
  140. elif not isinstance(applications, Mapping): # 单一任务函数 类型
  141. applications = {'index': applications}
  142. # covert dict key to str
  143. applications = {str(k): v for k, v in applications.items()}
  144. for app in applications.values():
  145. assert iscoroutinefunction(app) or isgeneratorfunction(app) or callable(app), \
  146. "Don't support application type:%s" % type(app)
  147. if 'index' not in applications:
  148. applications['index'] = _generate_default_index_app(applications)
  149. return applications
  150. class OriginChecker:
  151. @classmethod
  152. def check_origin(cls, origin, allowed_origins, host):
  153. if cls.is_same_site(origin, host):
  154. return True
  155. return any(
  156. fnmatch.fnmatch(origin, patten)
  157. for patten in allowed_origins
  158. )
  159. @staticmethod
  160. def is_same_site(origin, host):
  161. """判断 origin 和 host 是否一致。origin 和 host 都为http协议请求头"""
  162. parsed_origin = urllib.parse.urlparse(origin)
  163. origin = parsed_origin.netloc
  164. origin = origin.lower()
  165. # Check to see that origin matches host directly, including ports
  166. return origin == host
  167. def deserialize_binary_event(data: bytes):
  168. """
  169. Data format:
  170. | event | file_header | file_data | file_header | file_data | ...
  171. The 8 bytes at the beginning of each segment indicate the number of bytes remaining in the segment.
  172. event: {
  173. event: "from_submit",
  174. task_id: that.task_id,
  175. data: {
  176. input_name => input_data
  177. }
  178. }
  179. file_header: {
  180. 'filename': file name,
  181. 'size': file size,
  182. 'mime_type': file type,
  183. 'last_modified': last_modified timestamp,
  184. 'input_name': name of input field
  185. }
  186. Example:
  187. b'\x00\x00\x00\x00\x00\x00\x00E{"event":"from_submit","task_id":"main-4788341456","data":{"data":1}}\x00\x00\x00\x00\x00\x00\x00Y{"filename":"hello.txt","size":2,"mime_type":"text/plain","last_modified":1617119937.276}\x00\x00\x00\x00\x00\x00\x00\x02ss'
  188. """
  189. parts = []
  190. start_idx = 0
  191. while start_idx < len(data):
  192. size = int.from_bytes(data[start_idx:start_idx + 8], "big")
  193. start_idx += 8
  194. content = data[start_idx:start_idx + size]
  195. parts.append(content)
  196. start_idx += size
  197. event = json.loads(parts[0])
  198. files = defaultdict(list)
  199. for idx in range(1, len(parts), 2):
  200. f = json.loads(parts[idx])
  201. f['content'] = parts[idx + 1]
  202. input_name = f.pop('input_name')
  203. files[input_name].append(f)
  204. for input_name in list(event['data'].keys()):
  205. if input_name in files:
  206. event['data'][input_name] = files[input_name]
  207. return event
  208. def seo(title, description=None, app=None):
  209. """Set the SEO information of the PyWebIO application (web page information provided when indexed by search engines)
  210. :param str title: Application title
  211. :param str description: Application description
  212. :param callable app: PyWebIO task function
  213. If not ``seo()`` is not used, the `docstring <https://www.python.org/dev/peps/pep-0257/>`_ of the task function will be regarded as SEO information by default.
  214. ``seo()`` can be used in 2 ways: direct call and decorator::
  215. @seo("title", "description")
  216. def foo():
  217. pass
  218. def bar():
  219. pass
  220. def hello():
  221. \"""Application title
  222. Application description...
  223. (A empty line is used to separate the description and title)
  224. \"""
  225. start_server([
  226. foo,
  227. hello,
  228. seo("title", "description", bar),
  229. ])
  230. .. versionadded:: 1.1
  231. """
  232. if app is not None:
  233. return seo(title, description)(app)
  234. def decorator(func):
  235. try:
  236. func = partial(func)
  237. func._pywebio_title = title
  238. func._pywebio_description = description or ''
  239. except Exception:
  240. pass
  241. return func
  242. return decorator