page.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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,
  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 meta.title:
  64. meta = meta._replace(title=title, description=description)
  65. # fallback to global config
  66. for key in config_keys:
  67. if not getattr(meta, key, None) and _global_config.get(key):
  68. kwarg = {key: _global_config.get(key)}
  69. meta = meta._replace(**kwarg)
  70. return meta
  71. _app_list_tpl = template.Template("""
  72. <h1>Applications index</h1>
  73. <ul>
  74. {% for name,meta in apps_info.items() %}
  75. <li>
  76. {% if other_arguments is not None %}
  77. <a href="?app={{name}}{{other_arguments}}">{{ meta.title or name }}</a>:
  78. {% else %}
  79. <a href="javascript:WebIO.openApp('{{ name }}', true)">{{ meta.title or name }}</a>:
  80. {% end %}
  81. {% if meta.description %}
  82. {{ meta.description }}
  83. {% else %}
  84. <i>No description.</i>
  85. {% end %}
  86. </li>
  87. {% end %}
  88. </ul>
  89. """.strip())
  90. def get_static_index_content(apps, query_arguments=None):
  91. """生成默认的静态主页
  92. :param callable apps: PyWebIO apps
  93. :param str query_arguments: Url Query Arguments。为None时,表示使用WebIO.openApp跳转
  94. :return: bytes
  95. """
  96. apps_info = {
  97. name: parse_app_metadata(func)
  98. for name, func in apps.items()
  99. }
  100. qs = urllib.parse.parse_qs(query_arguments)
  101. qs.pop('app', None)
  102. other_arguments = urllib.parse.urlencode(qs, doseq=True)
  103. if other_arguments:
  104. other_arguments = '&' + other_arguments
  105. else:
  106. other_arguments = None
  107. content = _app_list_tpl.generate(apps_info=apps_info, other_arguments=other_arguments).decode('utf8')
  108. return content
  109. def _generate_default_index_app(apps):
  110. """默认的主页任务函数"""
  111. content = get_static_index_content(apps)
  112. def index():
  113. from pywebio.output import put_html
  114. put_html(content)
  115. return index
  116. def make_applications(applications):
  117. """格式化 applications 为 任务名->任务函数 的映射, 并提供默认主页
  118. :param applications: 接受 单一任务函数、字典、列表 类型
  119. :return dict: 任务名->任务函数 的映射
  120. """
  121. if isinstance(applications, Sequence): # 列表 类型
  122. applications, app_list = {}, applications
  123. for func in app_list:
  124. name = get_function_name(func)
  125. if name in applications:
  126. raise ValueError("Duplicated application name:%r" % name)
  127. applications[name] = func
  128. elif not isinstance(applications, Mapping): # 单一任务函数 类型
  129. applications = {'index': applications}
  130. # convert dict key to str
  131. applications = {str(k): v for k, v in applications.items()}
  132. for app in applications.values():
  133. assert iscoroutinefunction(app) or isgeneratorfunction(app) or callable(app), \
  134. "Don't support application type:%s" % type(app)
  135. if 'index' not in applications:
  136. applications['index'] = _generate_default_index_app(applications)
  137. return applications
  138. def seo(title, description=None, app=None):
  139. """Set the SEO information of the PyWebIO application (web page information provided when indexed by search engines)
  140. :param str title: Application title
  141. :param str description: Application description
  142. :param callable app: PyWebIO task function
  143. 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.
  144. ``seo()`` can be used in 2 ways: direct call and decorator::
  145. @seo("title", "description")
  146. def foo():
  147. pass
  148. def bar():
  149. pass
  150. def hello():
  151. \"""Application title
  152. Application description...
  153. (A empty line is used to separate the description and title)
  154. \"""
  155. start_server([
  156. foo,
  157. hello,
  158. seo("title", "description", bar),
  159. ])
  160. .. versionadded:: 1.1
  161. .. deprecated:: 1.4
  162. Use :func:`pywebio.config` instead.
  163. """
  164. import warnings
  165. warnings.warn("`pywebio.platform.seo()` is deprecated since v1.4 and will remove in the future version, "
  166. "use `pywebio.config` instead", DeprecationWarning, stacklevel=2)
  167. if app is not None:
  168. return config(title=title, description=description)(app)
  169. return config(title=title, description=description)
  170. def config(*, title=None, description=None, theme=None, js_code=None, js_file=[], css_style=None, css_file=[]):
  171. """PyWebIO application configuration
  172. :param str title: Application title
  173. :param str description: Application description
  174. :param str theme: Application theme. Available themes are: ``dark``, ``sketchy``, ``minty``, ``yeti``.
  175. You can also use environment variable ``PYWEBIO_THEME`` to specify the theme (with high priority).
  176. :demo_host:`Theme preview demo </theme>`
  177. .. collapse:: Open Source Credits
  178. The dark theme is modified from ForEvolve's `bootstrap-dark <https://github.com/ForEvolve/bootstrap-dark>`_.
  179. The sketchy, minty and yeti theme are from `bootswatch <https://bootswatch.com/4/>`_.
  180. :param str js_code: The javascript code that you want to inject to page.
  181. :param str/list js_file: The javascript files that inject to page, can be a URL in str or a list of it.
  182. :param str css_style: The CSS style that you want to inject to page.
  183. :param str/list css_file: The CSS files that inject to page, can be a URL in str or a list of it.
  184. ``config()`` can be used in 2 ways: direct call and decorator.
  185. If you call ``config()`` directly, the configuration will be global.
  186. If you use ``config()`` as decorator, the configuration will only work on single PyWebIO application function.
  187. ::
  188. config(title="My application") # global configuration
  189. @config(css_style="* { color:red }") # only works on this application
  190. def app():
  191. put_text("hello PyWebIO")
  192. .. note:: The configuration will affect all sessions
  193. ``title`` and ``description`` are used for SEO, which are provided when indexed by search engines.
  194. If no ``title`` and ``description`` set for a PyWebIO application function,
  195. the `docstring <https://www.python.org/dev/peps/pep-0257/>`_ of the function will be used as title and description by default::
  196. def app():
  197. \"""Application title
  198. Application description...
  199. (A empty line is used to separate the description and title)
  200. \"""
  201. pass
  202. The above code is equal to::
  203. @config(title="Application title", description="Application description...")
  204. def app():
  205. pass
  206. .. versionadded:: 1.4
  207. .. versionchanged:: 1.5
  208. add ``theme`` parameter
  209. """
  210. if isinstance(js_file, str):
  211. js_file = [js_file]
  212. if isinstance(css_file, str):
  213. css_file = [css_file]
  214. configs = locals()
  215. class Decorator:
  216. def __init__(self):
  217. self.called = False
  218. def __call__(self, func):
  219. self.called = True
  220. try:
  221. func = partial(func) # to make a copy of the function
  222. for key, val in configs.items():
  223. if val:
  224. setattr(func, '_pywebio_%s' % key, val)
  225. except Exception:
  226. pass
  227. return func
  228. def __del__(self): # if not called as decorator, set the config to global
  229. if self.called:
  230. return
  231. global _global_config
  232. _global_config = configs
  233. return Decorator()