page.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import urllib.parse
  2. from collections import namedtuple
  3. from collections.abc import Mapping, Sequence
  4. from functools import lru_cache
  5. from functools import partial
  6. from os import path, environ
  7. from tornado import template
  8. from ..__version__ import __version__ as version
  9. from ..utils import isgeneratorfunction, iscoroutinefunction, get_function_name, get_function_doc, \
  10. get_function_attr, STATIC_PATH
  11. """
  12. The maximum size in bytes of a http request body or a websocket message, after which the request or websocket is aborted
  13. Set by `start_server()` or `path_deploy()`
  14. Used in `file_upload()` as the `max_size`/`max_total_size` parameter default or to validate the parameter.
  15. """
  16. MAX_PAYLOAD_SIZE = 0
  17. DEFAULT_CDN = "https://cdn.jsdelivr.net/gh/wang0618/PyWebIO-assets@v{version}/"
  18. _global_config = {'title': 'PyWebIO Application'}
  19. config_keys = ['title', 'description', 'js_file', 'js_code', 'css_style', 'css_file', 'theme']
  20. AppMeta = namedtuple('App', config_keys)
  21. _here_dir = path.dirname(path.abspath(__file__))
  22. _index_page_tpl = template.Template(open(path.join(_here_dir, 'tpl', 'index.html'), encoding='utf8').read())
  23. def render_page(app, protocol, cdn):
  24. """渲染前端页面的HTML框架, 支持SEO
  25. :param callable app: PyWebIO app
  26. :param str protocol: 'ws'/'http'
  27. :param bool/str cdn: Whether to use CDN, also accept string as custom CDN URL
  28. :return: bytes content of rendered page
  29. """
  30. assert protocol in ('ws', 'http')
  31. meta = parse_app_metadata(app)
  32. if cdn is True:
  33. base_url = DEFAULT_CDN.format(version=version)
  34. elif not cdn:
  35. base_url = ''
  36. else: # user custom cdn
  37. base_url = cdn.rstrip('/') + '/'
  38. theme = environ.get('PYWEBIO_THEME', meta.theme) or 'default'
  39. check_theme(theme)
  40. return _index_page_tpl.generate(title=meta.title, description=meta.description, protocol=protocol,
  41. script=True, content='', base_url=base_url, version=version,
  42. js_file=meta.js_file or [], js_code=meta.js_code, css_style=meta.css_style,
  43. css_file=meta.css_file or [], theme=theme)
  44. @lru_cache(maxsize=64)
  45. def check_theme(theme):
  46. """check theme file existence"""
  47. if not theme:
  48. return
  49. theme_file = path.join(STATIC_PATH, 'css', 'bs-theme', theme + '.min.css')
  50. if not path.isfile(theme_file):
  51. raise RuntimeError("Can't find css file for theme `%s`" % theme)
  52. def parse_app_metadata(func):
  53. """Get metadata form pywebio task function, fallback to global config in empty meta field."""
  54. prefix = '_pywebio_'
  55. attrs = get_function_attr(func, [prefix + k for k in config_keys])
  56. meta = AppMeta(**{k: attrs.get(prefix + k) for k in config_keys})
  57. doc = get_function_doc(func)
  58. parts = doc.strip().split('\n\n', 1)
  59. if len(parts) == 2:
  60. title, description = parts
  61. else:
  62. title, description = parts[0], ''
  63. if not title:
  64. title = get_function_name(func)
  65. if not meta.title:
  66. meta = meta._replace(title=title, description=description)
  67. # fallback to global config
  68. for key in config_keys:
  69. if not getattr(meta, key, None) and _global_config.get(key):
  70. kwarg = {key: _global_config.get(key)}
  71. meta = meta._replace(**kwarg)
  72. return meta
  73. _app_list_tpl = template.Template("""
  74. <h1>Applications index</h1>
  75. <ul>
  76. {% for name,meta in apps_info.items() %}
  77. <li>
  78. {% if other_arguments is not None %}
  79. <a href="?app={{name}}{{other_arguments}}">{{ meta.title or name }}</a>:
  80. {% else %}
  81. <a href="javascript:WebIO.openApp('{{ name }}', true)">{{ meta.title or name }}</a>:
  82. {% end %}
  83. {% if meta.description %}
  84. {{ meta.description }}
  85. {% else %}
  86. <i>No description.</i>
  87. {% end %}
  88. </li>
  89. {% end %}
  90. </ul>
  91. """.strip())
  92. def get_static_index_content(apps, query_arguments=None):
  93. """生成默认的静态主页
  94. :param callable apps: PyWebIO apps
  95. :param str query_arguments: Url Query Arguments。为None时,表示使用WebIO.openApp跳转
  96. :return: bytes
  97. """
  98. apps_info = {
  99. name: parse_app_metadata(func)
  100. for name, func in apps.items()
  101. }
  102. qs = urllib.parse.parse_qs(query_arguments)
  103. qs.pop('app', None)
  104. other_arguments = urllib.parse.urlencode(qs, doseq=True)
  105. if other_arguments:
  106. other_arguments = '&' + other_arguments
  107. else:
  108. other_arguments = None
  109. content = _app_list_tpl.generate(apps_info=apps_info, other_arguments=other_arguments).decode('utf8')
  110. return content
  111. def _generate_default_index_app(apps):
  112. """默认的主页任务函数"""
  113. content = get_static_index_content(apps)
  114. def index():
  115. from pywebio.output import put_html
  116. put_html(content)
  117. return index
  118. def make_applications(applications):
  119. """格式化 applications 为 任务名->任务函数 的映射, 并提供默认主页
  120. :param applications: 接受 单一任务函数、字典、列表 类型
  121. :return dict: 任务名->任务函数 的映射
  122. """
  123. if isinstance(applications, Sequence): # 列表 类型
  124. applications, app_list = {}, applications
  125. for func in app_list:
  126. name = get_function_name(func)
  127. if name in applications:
  128. raise ValueError("Duplicated application name:%r" % name)
  129. applications[name] = func
  130. elif not isinstance(applications, Mapping): # 单一任务函数 类型
  131. applications = {'index': applications}
  132. # convert dict key to str
  133. applications = {str(k): v for k, v in applications.items()}
  134. for app in applications.values():
  135. assert iscoroutinefunction(app) or isgeneratorfunction(app) or callable(app), \
  136. "Don't support application type:%s" % type(app)
  137. if 'index' not in applications:
  138. applications['index'] = _generate_default_index_app(applications)
  139. return applications
  140. def seo(title, description=None, app=None):
  141. """Set the SEO information of the PyWebIO application (web page information provided when indexed by search engines)
  142. :param str title: Application title
  143. :param str description: Application description
  144. :param callable app: PyWebIO task function
  145. If ``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.
  146. ``seo()`` can be used in 2 ways: direct call and decorator::
  147. @seo("title", "description")
  148. def foo():
  149. pass
  150. def bar():
  151. pass
  152. def hello():
  153. \"""Application title
  154. Application description...
  155. (A empty line is used to separate the description and title)
  156. \"""
  157. start_server([
  158. foo,
  159. hello,
  160. seo("title", "description", bar),
  161. ])
  162. .. versionadded:: 1.1
  163. .. deprecated:: 1.4
  164. Use :func:`pywebio.config` instead.
  165. """
  166. import warnings
  167. warnings.warn("`pywebio.platform.seo()` is deprecated since v1.4 and will remove in the future version, "
  168. "use `pywebio.config` instead", DeprecationWarning, stacklevel=2)
  169. if app is not None:
  170. return config(title=title, description=description)(app)
  171. return config(title=title, description=description)
  172. def config(*, title=None, description=None, theme=None, js_code=None, js_file=[], css_style=None, css_file=[]):
  173. """PyWebIO application configuration
  174. :param str title: Application title
  175. :param str description: Application description
  176. :param str theme: Application theme. Available themes are: ``dark``, ``sketchy``, ``minty``, ``yeti``.
  177. You can also use environment variable ``PYWEBIO_THEME`` to specify the theme (with high priority).
  178. :demo_host:`Theme preview demo </theme>`
  179. .. collapse:: Open Source Credits
  180. The dark theme is modified from ForEvolve's `bootstrap-dark <https://github.com/ForEvolve/bootstrap-dark>`_.
  181. The sketchy, minty and yeti theme are from `bootswatch <https://bootswatch.com/4/>`_.
  182. :param str js_code: The javascript code that you want to inject to page.
  183. :param str/list js_file: The javascript files that inject to page, can be a URL in str or a list of it.
  184. :param str css_style: The CSS style that you want to inject to page.
  185. :param str/list css_file: The CSS files that inject to page, can be a URL in str or a list of it.
  186. ``config()`` can be used in 2 ways: direct call and decorator.
  187. If you call ``config()`` directly, the configuration will be global.
  188. If you use ``config()`` as decorator, the configuration will only work on single PyWebIO application function.
  189. ::
  190. config(title="My application") # global configuration
  191. @config(css_style="* { color:red }") # only works on this application
  192. def app():
  193. put_text("hello PyWebIO")
  194. .. note:: The configuration will affect all sessions
  195. ``title`` and ``description`` are used for SEO, which are provided when indexed by search engines.
  196. If no ``title`` and ``description`` set for a PyWebIO application function,
  197. the `docstring <https://www.python.org/dev/peps/pep-0257/>`_ of the function will be used as title and description by default::
  198. def app():
  199. \"""Application title
  200. Application description...
  201. (A empty line is used to separate the description and title)
  202. \"""
  203. pass
  204. The above code is equal to::
  205. @config(title="Application title", description="Application description...")
  206. def app():
  207. pass
  208. .. versionadded:: 1.4
  209. .. versionchanged:: 1.5
  210. add ``theme`` parameter
  211. """
  212. if isinstance(js_file, str):
  213. js_file = [js_file]
  214. if isinstance(css_file, str):
  215. css_file = [css_file]
  216. configs = locals()
  217. class Decorator:
  218. def __init__(self):
  219. self.called = False
  220. def __call__(self, func):
  221. self.called = True
  222. try:
  223. func = partial(func) # to make a copy of the function
  224. for key, val in configs.items():
  225. if val:
  226. setattr(func, '_pywebio_%s' % key, val)
  227. except Exception:
  228. pass
  229. return func
  230. def __del__(self): # if not called as decorator, set the config to global
  231. if self.called:
  232. return
  233. global _global_config
  234. _global_config = configs
  235. return Decorator()