1
0

page.py 12 KB

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