utils.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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
  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_seo_info
  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. AppMeta = namedtuple('App', 'title description')
  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. cdn = DEFAULT_CDN.format(version=version)
  35. elif not cdn:
  36. cdn = ''
  37. else: # user custom cdn
  38. cdn = cdn.rstrip('/') + '/'
  39. return _index_page_tpl.generate(title=meta.title or 'PyWebIO Application',
  40. description=meta.description, protocol=protocol,
  41. script=True, content='', base_url=cdn)
  42. def cdn_validation(cdn, level='warn', stacklevel=3):
  43. """CDN availability check
  44. :param bool/str cdn: cdn parameter
  45. :param level: warn or error
  46. """
  47. assert level in ('warn', 'error')
  48. if cdn is True and 'dev' in version:
  49. if level == 'warn':
  50. import warnings
  51. warnings.warn("Default CDN is not supported in dev version. Ignore the CDN setting", PyWebIOWarning,
  52. stacklevel=stacklevel)
  53. return False
  54. else:
  55. raise ValueError("Default CDN is not supported in dev version. Please host static files by yourself.")
  56. return cdn
  57. def parse_app_metadata(func):
  58. """解析pywebio app元数据"""
  59. seo_info = get_function_seo_info(func)
  60. if seo_info:
  61. return AppMeta(*seo_info)
  62. doc = get_function_doc(func)
  63. parts = doc.strip().split('\n\n', 1)
  64. if len(parts) == 2:
  65. title, description = parts
  66. else:
  67. title, description = parts[0], ''
  68. return AppMeta(title, description)
  69. _app_list_tpl = template.Template("""
  70. <h1>Applications index</h1>
  71. <ul>
  72. {% for name,meta in apps_info.items() %}
  73. <li>
  74. {% if other_arguments is not None %}
  75. <a href="?app={{name}}{{other_arguments}}">{{ meta.title or name }}</a>:
  76. {% else %}
  77. <a href="javascript:WebIO.openApp('{{ name }}', true)">{{ meta.title or name }}</a>:
  78. {% end %}
  79. {% if meta.description %}
  80. {{ meta.description }}
  81. {% else %}
  82. <i>No description.</i>
  83. {% end %}
  84. </li>
  85. {% end %}
  86. </ul>
  87. """.strip())
  88. def get_static_index_content(apps, query_arguments=None):
  89. """生成默认的静态主页
  90. :param callable apps: PyWebIO apps
  91. :param str query_arguments: Url Query Arguments。为None时,表示使用WebIO.openApp跳转
  92. :return: bytes
  93. """
  94. apps_info = {
  95. name: parse_app_metadata(func)
  96. for name, func in apps.items()
  97. }
  98. qs = urllib.parse.parse_qs(query_arguments)
  99. qs.pop('app', None)
  100. other_arguments = urllib.parse.urlencode(qs, doseq=True)
  101. if other_arguments:
  102. other_arguments = '&' + other_arguments
  103. else:
  104. other_arguments = None
  105. content = _app_list_tpl.generate(apps_info=apps_info, other_arguments=other_arguments).decode('utf8')
  106. return content
  107. def _generate_default_index_app(apps):
  108. """默认的主页任务函数"""
  109. content = get_static_index_content(apps)
  110. def index():
  111. from pywebio.output import put_html
  112. put_html(content)
  113. return index
  114. def make_applications(applications):
  115. """格式化 applications 为 任务名->任务函数 的映射, 并提供默认主页
  116. :param applications: 接受 单一任务函数、字典、列表 类型
  117. :return dict: 任务名->任务函数 的映射
  118. """
  119. if isinstance(applications, Sequence): # 列表 类型
  120. applications, app_list = {}, applications
  121. for func in app_list:
  122. name = get_function_name(func)
  123. if name in applications:
  124. raise ValueError("Duplicated application name:%r" % name)
  125. applications[name] = func
  126. elif not isinstance(applications, Mapping): # 单一任务函数 类型
  127. applications = {'index': applications}
  128. # covert dict key to str
  129. applications = {str(k): v for k, v in applications.items()}
  130. for app in applications.values():
  131. assert iscoroutinefunction(app) or isgeneratorfunction(app) or callable(app), \
  132. "Don't support application type:%s" % type(app)
  133. if 'index' not in applications:
  134. applications['index'] = _generate_default_index_app(applications)
  135. return applications
  136. class OriginChecker:
  137. @classmethod
  138. def check_origin(cls, origin, allowed_origins, host):
  139. if cls.is_same_site(origin, host):
  140. return True
  141. return any(
  142. fnmatch.fnmatch(origin, patten)
  143. for patten in allowed_origins
  144. )
  145. @staticmethod
  146. def is_same_site(origin, host):
  147. """判断 origin 和 host 是否一致。origin 和 host 都为http协议请求头"""
  148. parsed_origin = urllib.parse.urlparse(origin)
  149. origin = parsed_origin.netloc
  150. origin = origin.lower()
  151. # Check to see that origin matches host directly, including ports
  152. return origin == host
  153. def deserialize_binary_event(data: bytes):
  154. """
  155. Data format:
  156. | event | file_header | file_data | file_header | file_data | ...
  157. The 8 bytes at the beginning of each segment indicate the number of bytes remaining in the segment.
  158. event: {
  159. event: "from_submit",
  160. task_id: that.task_id,
  161. data: {
  162. input_name => input_data
  163. }
  164. }
  165. file_header: {
  166. 'filename': file name,
  167. 'size': file size,
  168. 'mime_type': file type,
  169. 'last_modified': last_modified timestamp,
  170. 'input_name': name of input field
  171. }
  172. Example:
  173. 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'
  174. """
  175. parts = []
  176. start_idx = 0
  177. while start_idx < len(data):
  178. size = int.from_bytes(data[start_idx:start_idx + 8], "big")
  179. start_idx += 8
  180. content = data[start_idx:start_idx + size]
  181. parts.append(content)
  182. start_idx += size
  183. event = json.loads(parts[0])
  184. files = defaultdict(list)
  185. for idx in range(1, len(parts), 2):
  186. f = json.loads(parts[idx])
  187. f['content'] = parts[idx + 1]
  188. input_name = f.pop('input_name')
  189. files[input_name].append(f)
  190. for input_name in list(event['data'].keys()):
  191. if input_name in files:
  192. event['data'][input_name] = files[input_name]
  193. return event
  194. def seo(title, description=None, app=None):
  195. """Set the SEO information of the PyWebIO application (web page information provided when indexed by search engines)
  196. :param str title: Application title
  197. :param str description: Application description
  198. :param callable app: PyWebIO task function
  199. 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.
  200. ``seo()`` can be used in 2 ways: direct call and decorator::
  201. @seo("title", "description")
  202. def foo():
  203. pass
  204. def bar():
  205. pass
  206. def hello():
  207. \"""Application title
  208. Application description...
  209. (A empty line is used to separate the description and title)
  210. \"""
  211. start_server([
  212. foo,
  213. hello,
  214. seo("title", "description", bar),
  215. ])
  216. .. versionadded:: 1.1
  217. """
  218. if app is not None:
  219. return seo(title, description)(app)
  220. def decorator(func):
  221. try:
  222. func = partial(func)
  223. func._pywebio_title = title
  224. func._pywebio_description = description or ''
  225. except Exception:
  226. pass
  227. return func
  228. return decorator