utils.py 7.0 KB

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