output.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. r"""输出内容到用户浏览器
  2. 本模块提供了一系列函数来输出不同形式的内容到用户浏览器,并支持灵活的输出控制。
  3. 输出控制
  4. --------------
  5. 锚点
  6. ^^^^^^^^^^^^^^^^^
  7. .. autofunction:: set_anchor
  8. .. autofunction:: clear_before
  9. .. autofunction:: clear_after
  10. .. autofunction:: clear_range
  11. .. autofunction:: scroll_to
  12. 环境设置
  13. ^^^^^^^^^^^^^^^^^
  14. .. autofunction:: set_title
  15. .. autofunction:: set_output_fixed_height
  16. .. autofunction:: set_auto_scroll_bottom
  17. 内容输出
  18. --------------
  19. .. autofunction:: put_text
  20. .. autofunction:: put_markdown
  21. .. autofunction:: put_code
  22. .. autofunction:: put_table
  23. .. autofunction:: table_cell_buttons
  24. .. autofunction:: put_buttons
  25. .. autofunction:: put_file
  26. """
  27. from base64 import b64encode
  28. from collections.abc import Mapping
  29. from .io_ctrl import output_register_callback, send_msg
  30. def set_title(title):
  31. r"""设置页面标题"""
  32. send_msg('output_ctl', dict(title=title))
  33. def set_output_fixed_height(enabled=True):
  34. r"""开启/关闭页面固高度模式"""
  35. send_msg('output_ctl', dict(output_fixed_height=enabled))
  36. def set_auto_scroll_bottom(enabled=True):
  37. r"""开启/关闭页面自动滚动到底部"""
  38. send_msg('output_ctl', dict(auto_scroll_bottom=enabled))
  39. _AnchorTPL = 'pywebio-anchor-%s'
  40. def set_anchor(name):
  41. """
  42. 在当前输出处标记锚点。 若已经存在 ``name`` 锚点,则先将旧锚点删除
  43. """
  44. inner_ancher_name = _AnchorTPL % name
  45. send_msg('output_ctl', dict(set_anchor=inner_ancher_name))
  46. def clear_before(anchor):
  47. """清除 ``anchor`` 锚点之前输出的内容"""
  48. inner_ancher_name = _AnchorTPL % anchor
  49. send_msg('output_ctl', dict(clear_before=inner_ancher_name))
  50. def clear_after(anchor):
  51. """清除 ``anchor`` 锚点之后输出的内容"""
  52. inner_ancher_name = _AnchorTPL % anchor
  53. send_msg('output_ctl', dict(clear_after=inner_ancher_name))
  54. def clear_range(start_anchor, end_anchor):
  55. """
  56. 清除 ``start_anchor`` - ``end_ancher`` 锚点之间输出的内容.
  57. 若 ``start_anchor`` 或 ``end_ancher`` 不存在,则不进行任何操作
  58. """
  59. inner_start_anchor_name = 'pywebio-anchor-%s' % start_anchor
  60. inner_end_ancher_name = 'pywebio-anchor-%s' % end_anchor
  61. send_msg('output_ctl', dict(clear_range=[inner_start_anchor_name, inner_end_ancher_name]))
  62. def scroll_to(anchor):
  63. """将页面滚动到 ``anchor`` 锚点处"""
  64. inner_ancher_name = 'pywebio-anchor-%s' % anchor
  65. send_msg('output_ctl', dict(scroll_to=inner_ancher_name))
  66. def _put_content(type, anchor=None, before=None, after=None, **other_spec):
  67. """
  68. 向用户端发送 ``output`` 指令
  69. :param type: 输出类型
  70. :param content: 输出内容
  71. :param anchor: 为当前的输出内容标记锚点
  72. :param before: 在给定的锚点之前输出内容
  73. :param after: 在给定的锚点之后输出内容。
  74. 注意: ``before`` 和 ``after`` 参数不可以同时使用
  75. :param other_spec: 额外的输出参数
  76. """
  77. assert not (before and after), "Parameter 'before' and 'after' cannot be specified at the same time"
  78. spec = dict(type=type)
  79. spec.update(other_spec)
  80. if anchor:
  81. spec['anchor'] = _AnchorTPL % anchor
  82. if before:
  83. spec['before'] = _AnchorTPL % before
  84. elif after:
  85. spec['after'] = _AnchorTPL % after
  86. send_msg("output", spec)
  87. def put_text(text, inline=False, anchor=None, before=None, after=None):
  88. """
  89. 输出文本内容
  90. :param str text: 文本内容
  91. :param str anchor: 为当前的输出内容标记锚点
  92. :param str before: 在给定的锚点之前输出内容
  93. :param str after: 在给定的锚点之后输出内容
  94. 注意: ``before`` 和 ``after`` 参数不可以同时使用
  95. """
  96. _put_content('text', content=text, inline=inline, anchor=anchor, before=before, after=after)
  97. def put_html(html, anchor=None, before=None, after=None):
  98. """
  99. 输出文本内容
  100. :param str html: html内容
  101. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  102. """
  103. _put_content('html', content=html, anchor=anchor, before=before, after=after)
  104. def put_code(content, langage='', anchor=None, before=None, after=None):
  105. """
  106. 输出代码块
  107. :param str content: 代码内容
  108. :param str langage: 代码语言
  109. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  110. """
  111. code = "```%s\n%s\n```" % (langage, content)
  112. put_markdown(code, anchor=anchor, before=before, after=after)
  113. def put_markdown(mdcontent, strip_indent=0, lstrip=False, anchor=None, before=None, after=None):
  114. """
  115. 输出Markdown内容。
  116. :param str mdcontent: Markdown文本
  117. :param int strip_indent: 对于每一行,若前 ``strip_indent`` 个字符都为空格,则将其去除
  118. :param bool lstrip: 是否去除每一行开始的空白符
  119. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  120. 当在函数中使用Python的三引号语法输出多行内容时,为了排版美观可能会对Markdown文本进行缩进,
  121. 这时候,可以设置 ``strip_indent`` 或 ``lstrip`` 来防止Markdown错误解析(但不要同时使用 ``strip_indent`` 和 ``lstrip`` )::
  122. # 不使用strip_indent或lstrip
  123. def hello():
  124. put_markdown(r\""" # H1
  125. This is content.
  126. \""")
  127. # 使用lstrip
  128. def hello():
  129. put_markdown(r\""" # H1
  130. This is content.
  131. \""", lstrip=True)
  132. # 使用strip_indent
  133. def hello():
  134. put_markdown(r\""" # H1
  135. This is content.
  136. \""", strip_indent=4)
  137. """
  138. if strip_indent:
  139. lines = (
  140. i[strip_indent:] if (i[:strip_indent] == ' ' * strip_indent) else i
  141. for i in mdcontent.splitlines()
  142. )
  143. mdcontent = '\n'.join(lines)
  144. if lstrip:
  145. lines = (i.lstrip() for i in mdcontent.splitlines())
  146. mdcontent = '\n'.join(lines)
  147. _put_content('markdown', content=mdcontent, anchor=anchor, before=before, after=after)
  148. def put_table(tdata, header=None, anchor=None, before=None, after=None):
  149. """
  150. 输出表格
  151. :param list tdata: 表格数据。列表项可以为 ``list`` 或者 ``dict``
  152. :param list header: 设定表头。
  153. 当 ``tdata`` 的列表项为 ``list`` 类型时,若省略 ``header`` 参数,则使用 ``tdata`` 的第一项作为表头。
  154. 当 ``tdata`` 为字典列表时,使用 ``header`` 指定表头顺序,不可省略。
  155. 此时, ``header`` 格式可以为 <字典键>列表 或者 ``(<显示文本>, <字典键>)`` 列表。
  156. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  157. 使用示例::
  158. put_table([
  159. ['Name', 'Gender', 'Address'],
  160. ['Wang', 'M', 'China'],
  161. ['Liu', 'W', 'America'],
  162. ])
  163. put_table([
  164. ['Wang', 'M', 'China'],
  165. ['Liu', 'W', 'America'],
  166. ], header=['Name', 'Gender', 'Address'])
  167. put_table([
  168. {"Course":"OS", "Score": "80"},
  169. {"Course":"DB", "Score": "93"},
  170. ], header=["Course", "Score"]) # or header=[("课程", "Course"), ("得分" ,"Score")]
  171. """
  172. # Change ``dict`` row table to list row table
  173. if tdata and isinstance(tdata[0], dict):
  174. if isinstance(header[0], (list, tuple)):
  175. header_ = [h[0] for h in header]
  176. order = [h[-1] for h in header]
  177. else:
  178. header_ = order = header
  179. tdata = [
  180. [row.get(k, '') for k in order]
  181. for row in tdata
  182. ]
  183. header = header_
  184. if not header:
  185. header = tdata[0]
  186. tdata = tdata[1:]
  187. # 防止当tdata只有一行时,无法显示表格
  188. if len(tdata) == 0:
  189. raise ValueError("No data in table")
  190. def quote(data):
  191. return str(data).replace('|', r'\|')
  192. header_row = "|%s|" % "|".join(map(quote, header))
  193. rows = [header_row]
  194. rows.append("|%s|" % "|".join(['----'] * len(header)))
  195. for tr in tdata:
  196. t = "|%s|" % "|".join(map(quote, tr))
  197. rows.append(t)
  198. put_markdown('\n'.join(rows), anchor=anchor, before=before, after=after)
  199. def _format_button(buttons):
  200. """
  201. 格式化按钮参数
  202. :param buttons: button列表, button可用形式:
  203. {label:, value:, }
  204. (label, value, )
  205. value 单值,label等于value
  206. :return: [{value:, label:, }, ...]
  207. """
  208. btns = []
  209. for btn in buttons:
  210. if isinstance(btn, Mapping):
  211. assert 'value' in btn and 'label' in btn, 'actions item must have value and label key'
  212. elif isinstance(btn, (list, tuple)):
  213. assert len(btn) == 2, 'actions item format error'
  214. btn = dict(zip(('label', 'value'), btn))
  215. else:
  216. btn = dict(value=btn, label=btn)
  217. btns.append(btn)
  218. return btns
  219. def table_cell_buttons(buttons, onclick, **callback_options):
  220. """
  221. 在表格中显示一组按钮
  222. :param str buttons, onclick, save: 与 `put_buttons` 函数的同名参数含义一致
  223. .. _table_cell_buttons-code-sample:
  224. 使用示例::
  225. from functools import partial
  226. def edit_row(choice, row):
  227. put_text("You click %s button ar row %s" % (choice, row))
  228. put_table([
  229. ['Idx', 'Actions'],
  230. ['1', table_cell_buttons(['edit', 'delete'], onclick=partial(edit_row, row=1))],
  231. ['2', table_cell_buttons(['edit', 'delete'], onclick=partial(edit_row, row=2))],
  232. ['3', table_cell_buttons(['edit', 'delete'], onclick=partial(edit_row, row=3))],
  233. ])
  234. """
  235. btns = _format_button(buttons)
  236. callback_id = output_register_callback(onclick, **callback_options)
  237. tpl = '<button type="button" value="{value}" class="btn btn-primary btn-sm" ' \
  238. 'onclick="WebIO.DisplayAreaButtonOnClick(this, \'%s\')">{label}</button>' % callback_id
  239. btns_html = [tpl.format(**b) for b in btns]
  240. return ' '.join(btns_html)
  241. def put_buttons(buttons, onclick, small=False, anchor=None, before=None, after=None, **callback_options):
  242. """
  243. 输出一组按钮
  244. :param list buttons: 按钮列表。列表项的可用形式有:
  245. * dict: ``{label:选项标签, value:选项值}``
  246. * tuple or list: ``(label, value)``
  247. * 单值: 此时label和value使用相同的值
  248. :type onclick: Callable or Coroutine
  249. :param onclick: 按钮点击回调函数. ``onclick`` 可以是普通函数或者协程函数.
  250. 函数签名为 ``onclick(btn_value)``.
  251. 当按钮组中的按钮被点击时,``onclick`` 被调用,并传入被点击的按钮的 ``value`` 值。
  252. 可以使用 ``functools.partial`` 来在 ``onclick`` 中保存更多上下文信息,见 `table_cell_buttons` :ref:`代码示例 <table_cell_buttons-code-sample>` 。
  253. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  254. :param callback_options: 回调函数的其他参数。根据选用的 session 实现有不同参数
  255. CoroutineBasedSession 实现
  256. * mutex_mode: 互斥模式。若为 ``True`` ,则在运行回调函数过程中,无法响应当前按钮组的新点击事件,仅当 ``onclick`` 为协程函数时有效
  257. ThreadBasedSession 实现
  258. * serial_mode: 串行模式模式。若为 ``True`` ,则对于同一组件的点击事件,串行执行其回调函数。
  259. 不开启 ``serial_mode`` 时,ThreadBasedSession 在新线程中执行回调函数。所以如果回调函数运行时间很短,
  260. 可以关闭 ``serial_mode`` 来提高性能。
  261. """
  262. assert not (before and after), "Parameter 'before' and 'after' cannot be specified at the same time"
  263. btns = _format_button(buttons)
  264. callback_id = output_register_callback(onclick, **callback_options)
  265. _put_content('buttons', callback_id=callback_id, buttons=btns, small=small, anchor=anchor, before=before,
  266. after=after)
  267. def put_file(name, content, anchor=None, before=None, after=None):
  268. """输出文件。
  269. 在浏览器上的显示为一个以文件名为名的链接,点击链接后浏览器自动下载文件。
  270. :param str name: 文件名
  271. :param content: 文件内容. 类型为 bytes-like object
  272. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  273. """
  274. assert not (before and after), "Parameter 'before' and 'after' cannot be specified at the same time"
  275. content = b64encode(content).decode('ascii')
  276. _put_content('file', name=name, content=content, anchor=anchor, before=before, after=after)