utils.py 13 KB

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