utils.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import urllib.parse
  2. from collections import namedtuple
  3. from collections.abc import Mapping, Sequence
  4. from functools import partial
  5. from os import path
  6. from tornado import template
  7. from ..__version__ import __version__ as version
  8. from ..exceptions import PyWebIOWarning
  9. from ..utils import isgeneratorfunction, iscoroutinefunction, get_function_name, get_function_doc, \
  10. get_function_seo_info
  11. DEFAULT_CDN = "https://cdn.jsdelivr.net/gh/wang0618/PyWebIO-assets@v{version}/"
  12. AppMeta = namedtuple('App', 'title description')
  13. _here_dir = path.dirname(path.abspath(__file__))
  14. _index_page_tpl = template.Template(open(path.join(_here_dir, 'tpl', 'index.html')).read())
  15. def render_page(app, protocol, cdn):
  16. """渲染前端页面的HTML框架, 支持SEO
  17. :param callable app: PyWebIO app
  18. :param str protocol: 'ws'/'http'
  19. :param bool/str cdn: Whether to use CDN, also accept string as custom CDN URL
  20. :return: bytes content of rendered page
  21. """
  22. assert protocol in ('ws', 'http')
  23. meta = parse_app_metadata(app)
  24. if cdn is True:
  25. cdn = DEFAULT_CDN.format(version=version)
  26. elif not cdn:
  27. cdn = ''
  28. return _index_page_tpl.generate(title=meta.title or 'PyWebIO Application',
  29. description=meta.description, protocol=protocol,
  30. script=True, content='', base_url=cdn)
  31. def cdn_validation(cdn, level='warn'):
  32. """CDN availability check
  33. :param bool/str cdn: cdn parameter
  34. :param level: warn or error
  35. """
  36. assert level in ('warn', 'error')
  37. if cdn is True and 'dev' in version:
  38. if level == 'warn':
  39. import warnings
  40. warnings.warn("Default CDN is not supported in dev version. Ignore the CDN setting", PyWebIOWarning,
  41. stacklevel=3)
  42. return False
  43. else:
  44. raise ValueError("Default CDN is not supported in dev version. Please host static files by yourself.")
  45. return cdn
  46. def parse_app_metadata(func):
  47. """解析pywebio app元数据"""
  48. seo_info = get_function_seo_info(func)
  49. if seo_info:
  50. return AppMeta(*seo_info)
  51. doc = get_function_doc(func)
  52. parts = doc.strip().split('\n\n', 1)
  53. if len(parts) == 2:
  54. title, description = parts
  55. else:
  56. title, description = parts[0], ''
  57. return AppMeta(title, description)
  58. _app_list_tpl = template.Template("""
  59. <h1>Applications index</h1>
  60. <ul>
  61. {% for name,meta in apps_info.items() %}
  62. <li>
  63. {% if other_arguments is not None %}
  64. <a href="?app={{name}}{{other_arguments}}">{{ meta.title or name }}</a>:
  65. {% else %}
  66. <a href="javascript:WebIO.openApp('{{ name }}', true)">{{ meta.title or name }}</a>:
  67. {% end %}
  68. {% if meta.description %}
  69. {{ meta.description }}
  70. {% else %}
  71. <i>No description.</i>
  72. {% end %}
  73. </li>
  74. {% end %}
  75. </ul>
  76. """.strip())
  77. def get_static_index_content(apps, query_arguments=None):
  78. """生成默认的静态主页
  79. :param callable apps: PyWebIO apps
  80. :param str query_arguments: Url Query Arguments。为None时,表示使用WebIO.openApp跳转
  81. :return: bytes
  82. """
  83. apps_info = {
  84. name: parse_app_metadata(func)
  85. for name, func in apps.items()
  86. }
  87. qs = urllib.parse.parse_qs(query_arguments)
  88. qs.pop('app', None)
  89. other_arguments = urllib.parse.urlencode(qs, doseq=True)
  90. if other_arguments:
  91. other_arguments = '&' + other_arguments
  92. else:
  93. other_arguments = None
  94. content = _app_list_tpl.generate(apps_info=apps_info, other_arguments=other_arguments).decode('utf8')
  95. return content
  96. def _generate_default_index_app(apps):
  97. """默认的主页任务函数"""
  98. content = get_static_index_content(apps)
  99. def index():
  100. from pywebio.output import put_html
  101. put_html(content)
  102. return index
  103. def make_applications(applications):
  104. """格式化 applications 为 任务名->任务函数 的映射, 并提供默认主页
  105. :param applications: 接受 单一任务函数、字典、列表 类型
  106. :return dict: 任务名->任务函数 的映射
  107. """
  108. if isinstance(applications, Sequence): # 列表 类型
  109. applications, app_list = {}, applications
  110. for func in app_list:
  111. name = get_function_name(func)
  112. if name in applications:
  113. raise ValueError("Duplicated application name:%r" % name)
  114. applications[name] = func
  115. elif not isinstance(applications, Mapping): # 单一任务函数 类型
  116. applications = {'index': applications}
  117. # covert dict key to str
  118. applications = {str(k): v for k, v in applications.items()}
  119. for app in applications.values():
  120. assert iscoroutinefunction(app) or isgeneratorfunction(app) or callable(app), \
  121. "Don't support application type:%s" % type(app)
  122. if 'index' not in applications:
  123. applications['index'] = _generate_default_index_app(applications)
  124. return applications
  125. def seo(title, description=None, app=None):
  126. '''Set the SEO information of the PyWebIO application (web page information provided when indexed by search engines)
  127. :param str title: Application title
  128. :param str description: Application description
  129. :param callable app: PyWebIO task function
  130. 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.
  131. ``seo()`` can be used in 2 ways: direct call and decorator::
  132. @seo("title", "description")
  133. def foo():
  134. pass
  135. def bar():
  136. pass
  137. def hello():
  138. """Application title
  139. Application description...
  140. (A empty line is used to separate the description and title)
  141. """
  142. start_server([
  143. foo,
  144. hello,
  145. seo("title", "description", bar),
  146. ])
  147. '''
  148. if app is not None:
  149. return seo(title, description)(app)
  150. def decorator(func):
  151. try:
  152. func = partial(func)
  153. func._pywebio_title = title
  154. func._pywebio_description = description or ''
  155. except Exception:
  156. pass
  157. return func
  158. return decorator