1
0

utils.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from collections.abc import Mapping, Sequence
  2. from ..utils import isgeneratorfunction, iscoroutinefunction, get_function_name
  3. import inspect
  4. def _generate_index(applications):
  5. """生成默认的主页任务函数"""
  6. md_text = "## Application index\n"
  7. for name, task in applications.items():
  8. # todo 保留当前页面的设置项
  9. md_text += "- [{name}](?app={name}): {desc}\n".format(name=name, desc=(inspect.getdoc(task) or ''))
  10. def index():
  11. from pywebio.output import put_markdown
  12. put_markdown(md_text)
  13. return index
  14. def make_applications(applications):
  15. """格式化 applications 为 任务名->任务函数 的映射, 并提供默认主页
  16. :param applications: 接受 单一任务函数、字典、列表 类型
  17. :return dict: 任务名->任务函数 的映射
  18. """
  19. if isinstance(applications, Sequence): # 列表 类型
  20. applications = {get_function_name(func): func for func in applications}
  21. elif not isinstance(applications, Mapping): # 单一任务函数 类型
  22. applications = {'index': applications}
  23. for app in applications.values():
  24. assert iscoroutinefunction(app) or isgeneratorfunction(app) or callable(app), \
  25. "Don't support application type:%s" % type(app)
  26. if 'index' not in applications:
  27. applications['index'] = _generate_index(applications)
  28. return applications