utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import fnmatch
  2. import json
  3. import urllib.parse
  4. from collections import defaultdict
  5. from collections import namedtuple
  6. from collections.abc import Mapping, Sequence
  7. from functools import partial
  8. from os import path, environ
  9. from tornado import template
  10. from functools import lru_cache
  11. from ..__version__ import __version__ as version
  12. from ..exceptions import PyWebIOWarning
  13. from ..utils import isgeneratorfunction, iscoroutinefunction, get_function_name, get_function_doc, \
  14. get_function_attr, STATIC_PATH
  15. """
  16. The maximum size in bytes of a http request body or a websocket message, after which the request or websocket is aborted
  17. Set by `start_server()` or `path_deploy()`
  18. Used in `file_upload()` as the `max_size`/`max_total_size` parameter default or to validate the parameter.
  19. """
  20. MAX_PAYLOAD_SIZE = 0
  21. DEFAULT_CDN = "https://cdn.jsdelivr.net/gh/wang0618/PyWebIO-assets@v{version}/"
  22. _global_config = {'title': 'PyWebIO Application'}
  23. config_keys = ['title', 'description', 'js_file', 'js_code', 'css_style', 'css_file', 'theme']
  24. AppMeta = namedtuple('App', config_keys)
  25. _here_dir = path.dirname(path.abspath(__file__))
  26. _index_page_tpl = template.Template(open(path.join(_here_dir, 'tpl', 'index.html'), encoding='utf8').read())
  27. def render_page(app, protocol, cdn):
  28. """渲染前端页面的HTML框架, 支持SEO
  29. :param callable app: PyWebIO app
  30. :param str protocol: 'ws'/'http'
  31. :param bool/str cdn: Whether to use CDN, also accept string as custom CDN URL
  32. :return: bytes content of rendered page
  33. """
  34. assert protocol in ('ws', 'http')
  35. meta = parse_app_metadata(app)
  36. if cdn is True:
  37. base_url = DEFAULT_CDN.format(version=version)
  38. elif not cdn:
  39. base_url = ''
  40. else: # user custom cdn
  41. base_url = cdn.rstrip('/') + '/'
  42. theme = environ.get('PYWEBIO_THEME', meta.theme)
  43. check_theme(theme)
  44. return _index_page_tpl.generate(title=meta.title, description=meta.description, protocol=protocol,
  45. script=True, content='', base_url=base_url,
  46. js_file=meta.js_file or [], js_code=meta.js_code, css_style=meta.css_style,
  47. css_file=meta.css_file or [], theme=theme)
  48. @lru_cache(maxsize=64)
  49. def check_theme(theme):
  50. """check theme file existence"""
  51. if not theme:
  52. return
  53. theme_file = path.join(STATIC_PATH, 'css', 'bs-theme', theme + '.min.css')
  54. if not path.isfile(theme_file):
  55. raise RuntimeError("Can't find css file for theme `%s`" % theme)
  56. def cdn_validation(cdn, level='warn', stacklevel=3):
  57. """CDN availability check
  58. :param bool/str cdn: cdn parameter
  59. :param level: warn or error
  60. """
  61. assert level in ('warn', 'error')
  62. if cdn is True and 'dev' in version:
  63. if level == 'warn':
  64. import warnings
  65. warnings.warn("Default CDN is not supported in dev version. Ignore the CDN setting", PyWebIOWarning,
  66. stacklevel=stacklevel)
  67. return False
  68. else:
  69. raise ValueError("Default CDN is not supported in dev version. Please host static files by yourself.")
  70. return cdn
  71. def parse_app_metadata(func):
  72. """Get metadata form pywebio task function, fallback to global config in empty meta field."""
  73. prefix = '_pywebio_'
  74. attrs = get_function_attr(func, [prefix + k for k in config_keys])
  75. meta = AppMeta(**{k: attrs.get(prefix + k) for k in config_keys})
  76. doc = get_function_doc(func)
  77. parts = doc.strip().split('\n\n', 1)
  78. if len(parts) == 2:
  79. title, description = parts
  80. else:
  81. title, description = parts[0], ''
  82. if not meta.title:
  83. meta = meta._replace(title=title, description=description)
  84. # fallback to global config
  85. for key in config_keys:
  86. if not getattr(meta, key, None) and _global_config.get(key):
  87. kwarg = {key: _global_config.get(key)}
  88. meta = meta._replace(**kwarg)
  89. return meta
  90. _app_list_tpl = template.Template("""
  91. <h1>Applications index</h1>
  92. <ul>
  93. {% for name,meta in apps_info.items() %}
  94. <li>
  95. {% if other_arguments is not None %}
  96. <a href="?app={{name}}{{other_arguments}}">{{ meta.title or name }}</a>:
  97. {% else %}
  98. <a href="javascript:WebIO.openApp('{{ name }}', true)">{{ meta.title or name }}</a>:
  99. {% end %}
  100. {% if meta.description %}
  101. {{ meta.description }}
  102. {% else %}
  103. <i>No description.</i>
  104. {% end %}
  105. </li>
  106. {% end %}
  107. </ul>
  108. """.strip())
  109. def get_static_index_content(apps, query_arguments=None):
  110. """生成默认的静态主页
  111. :param callable apps: PyWebIO apps
  112. :param str query_arguments: Url Query Arguments。为None时,表示使用WebIO.openApp跳转
  113. :return: bytes
  114. """
  115. apps_info = {
  116. name: parse_app_metadata(func)
  117. for name, func in apps.items()
  118. }
  119. qs = urllib.parse.parse_qs(query_arguments)
  120. qs.pop('app', None)
  121. other_arguments = urllib.parse.urlencode(qs, doseq=True)
  122. if other_arguments:
  123. other_arguments = '&' + other_arguments
  124. else:
  125. other_arguments = None
  126. content = _app_list_tpl.generate(apps_info=apps_info, other_arguments=other_arguments).decode('utf8')
  127. return content
  128. def _generate_default_index_app(apps):
  129. """默认的主页任务函数"""
  130. content = get_static_index_content(apps)
  131. def index():
  132. from pywebio.output import put_html
  133. put_html(content)
  134. return index
  135. def make_applications(applications):
  136. """格式化 applications 为 任务名->任务函数 的映射, 并提供默认主页
  137. :param applications: 接受 单一任务函数、字典、列表 类型
  138. :return dict: 任务名->任务函数 的映射
  139. """
  140. if isinstance(applications, Sequence): # 列表 类型
  141. applications, app_list = {}, applications
  142. for func in app_list:
  143. name = get_function_name(func)
  144. if name in applications:
  145. raise ValueError("Duplicated application name:%r" % name)
  146. applications[name] = func
  147. elif not isinstance(applications, Mapping): # 单一任务函数 类型
  148. applications = {'index': applications}
  149. # convert dict key to str
  150. applications = {str(k): v for k, v in applications.items()}
  151. for app in applications.values():
  152. assert iscoroutinefunction(app) or isgeneratorfunction(app) or callable(app), \
  153. "Don't support application type:%s" % type(app)
  154. if 'index' not in applications:
  155. applications['index'] = _generate_default_index_app(applications)
  156. return applications
  157. class OriginChecker:
  158. @classmethod
  159. def check_origin(cls, origin, allowed_origins, host):
  160. if cls.is_same_site(origin, host):
  161. return True
  162. return any(
  163. fnmatch.fnmatch(origin, pattern)
  164. for pattern in allowed_origins
  165. )
  166. @staticmethod
  167. def is_same_site(origin, host):
  168. """判断 origin 和 host 是否一致。origin 和 host 都为http协议请求头"""
  169. parsed_origin = urllib.parse.urlparse(origin)
  170. origin = parsed_origin.netloc
  171. origin = origin.lower()
  172. # Check to see that origin matches host directly, including ports
  173. return origin == host
  174. def deserialize_binary_event(data: bytes):
  175. """
  176. Data format:
  177. | event | file_header | file_data | file_header | file_data | ...
  178. The 8 bytes at the beginning of each segment indicate the number of bytes remaining in the segment.
  179. event: {
  180. event: "from_submit",
  181. task_id: that.task_id,
  182. data: {
  183. input_name => input_data
  184. }
  185. }
  186. file_header: {
  187. 'filename': file name,
  188. 'size': file size,
  189. 'mime_type': file type,
  190. 'last_modified': last_modified timestamp,
  191. 'input_name': name of input field
  192. }
  193. Example:
  194. b'\x00\x00\x00\x00\x00\x00\x00E{"event":"from_submit","task_id":"main-4788341456","data":{"data":1}}\x00\x00\x00\x00\x00\x00\x00Y{"filename":"hello.txt","size":2,"mime_type":"text/plain","last_modified":1617119937.276}\x00\x00\x00\x00\x00\x00\x00\x02ss'
  195. """
  196. parts = []
  197. start_idx = 0
  198. while start_idx < len(data):
  199. size = int.from_bytes(data[start_idx:start_idx + 8], "big")
  200. start_idx += 8
  201. content = data[start_idx:start_idx + size]
  202. parts.append(content)
  203. start_idx += size
  204. event = json.loads(parts[0])
  205. files = defaultdict(list)
  206. for idx in range(1, len(parts), 2):
  207. f = json.loads(parts[idx])
  208. f['content'] = parts[idx + 1]
  209. input_name = f.pop('input_name')
  210. files[input_name].append(f)
  211. for input_name in list(event['data'].keys()):
  212. if input_name in files:
  213. event['data'][input_name] = files[input_name]
  214. return event
  215. def seo(title, description=None, app=None):
  216. """Set the SEO information of the PyWebIO application (web page information provided when indexed by search engines)
  217. :param str title: Application title
  218. :param str description: Application description
  219. :param callable app: PyWebIO task function
  220. 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.
  221. ``seo()`` can be used in 2 ways: direct call and decorator::
  222. @seo("title", "description")
  223. def foo():
  224. pass
  225. def bar():
  226. pass
  227. def hello():
  228. \"""Application title
  229. Application description...
  230. (A empty line is used to separate the description and title)
  231. \"""
  232. start_server([
  233. foo,
  234. hello,
  235. seo("title", "description", bar),
  236. ])
  237. .. versionadded:: 1.1
  238. .. deprecated:: 1.4
  239. Use :func:`pywebio.config` instead.
  240. """
  241. import warnings
  242. warnings.warn("`pywebio.platform.seo()` is deprecated since v1.4 and will remove in the future version, "
  243. "use `pywebio.config` instead", DeprecationWarning, stacklevel=2)
  244. if app is not None:
  245. return config(title=title, description=description)(app)
  246. return config(title=title, description=description)
  247. def config(*, title=None, description=None, theme=None, js_code=None, js_file=[], css_style=None, css_file=[]):
  248. """PyWebIO application configuration
  249. :param str title: Application title
  250. :param str description: Application description
  251. :param str theme: Application theme. Available themes are: ``dark``, ``sketchy``, ``lux``.
  252. You can also use environment variable ``PYWEBIO_THEME`` to specify the theme (with high priority).
  253. .. collapse:: Open Source Credits
  254. The dark theme is modified from ForEvolve's `bootstrap-dark <https://github.com/ForEvolve/bootstrap-dark>`_.
  255. The rest of the themes are from `bootswatch <https://bootswatch.com/4/>`_.
  256. :param str js_code: The javascript code that you want to inject to page.
  257. :param str/list js_file: The javascript files that inject to page, can be a URL in str or a list of it.
  258. :param str css_style: The CSS style that you want to inject to page.
  259. :param str/list css_file: The CSS files that inject to page, can be a URL in str or a list of it.
  260. ``config()`` can be used in 2 ways: direct call and decorator.
  261. If you call ``config()`` directly, the configuration will be global.
  262. If you use ``config()`` as decorator, the configuration will only work on single PyWebIO application function.
  263. ::
  264. config(title="My application")
  265. @config(css_style="* { color:red }")
  266. def app():
  267. put_text("hello PyWebIO")
  268. ``title`` and ``description`` are used for SEO, which are provided when indexed by search engines.
  269. If no ``title`` and ``description`` set for a PyWebIO application function,
  270. the `docstring <https://www.python.org/dev/peps/pep-0257/>`_ of the function will be used as title and description by default::
  271. def app():
  272. \"""Application title
  273. Application description...
  274. (A empty line is used to separate the description and title)
  275. \"""
  276. pass
  277. The above code is equal to::
  278. @config(title="Application title", description="Application description...")
  279. def app():
  280. pass
  281. .. versionadded:: 1.4
  282. .. versionchanged:: 1.5
  283. add ``theme`` parameter
  284. """
  285. if isinstance(js_file, str):
  286. js_file = [js_file]
  287. if isinstance(css_file, str):
  288. css_file = [css_file]
  289. configs = locals()
  290. class Decorator:
  291. def __init__(self):
  292. self.called = False
  293. def __call__(self, func):
  294. self.called = True
  295. try:
  296. func = partial(func) # to make a copy of the function
  297. for key, val in configs.items():
  298. if val:
  299. setattr(func, '_pywebio_%s' % key, val)
  300. except Exception:
  301. pass
  302. return func
  303. def __del__(self): # if not called as decorator, set the config to global
  304. if self.called:
  305. return
  306. global _global_config
  307. _global_config = configs
  308. return Decorator()