output.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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:: remove
  12. .. autofunction:: scroll_to
  13. 环境设置
  14. ^^^^^^^^^^^^^^^^^
  15. .. autofunction:: set_title
  16. .. autofunction:: set_output_fixed_height
  17. .. autofunction:: set_auto_scroll_bottom
  18. 内容输出
  19. --------------
  20. .. autofunction:: put_text
  21. .. autofunction:: put_markdown
  22. .. autofunction:: put_html
  23. .. autofunction:: put_code
  24. .. autofunction:: put_table
  25. .. autofunction:: table_cell_buttons
  26. .. autofunction:: put_buttons
  27. .. autofunction:: put_image
  28. .. autofunction:: put_file
  29. """
  30. import io
  31. from base64 import b64encode
  32. from collections.abc import Mapping
  33. from .io_ctrl import output_register_callback, send_msg, OutputReturn
  34. try:
  35. from PIL.Image import Image as PILImage
  36. except ImportError:
  37. PILImage = type('MockPILImage', (), dict(__init__=None))
  38. __all__ = ['TOP', 'MIDDLE', 'BOTTOM', 'set_title', 'set_output_fixed_height', 'set_auto_scroll_bottom', 'set_anchor',
  39. 'clear_before', 'clear_after', 'clear_range', 'remove', 'scroll_to', 'put_text', 'put_html',
  40. 'put_code', 'put_markdown', 'put_table', 'table_cell_buttons', 'put_buttons', 'put_image', 'put_file']
  41. TOP = 'top'
  42. MIDDLE = 'middle'
  43. BOTTOM = 'bottom'
  44. def set_title(title):
  45. r"""设置页面标题"""
  46. send_msg('output_ctl', dict(title=title))
  47. def set_output_fixed_height(enabled=True):
  48. r"""开启/关闭页面固高度模式"""
  49. send_msg('output_ctl', dict(output_fixed_height=enabled))
  50. def set_auto_scroll_bottom(enabled=True):
  51. r"""开启/关闭页面自动滚动到底部"""
  52. send_msg('output_ctl', dict(auto_scroll_bottom=enabled))
  53. def _get_anchor_id(name):
  54. """获取实际用于前端html页面中的id属性"""
  55. name = name.replace(' ', '-')
  56. return 'pywebio-anchor-%s' % name
  57. def set_anchor(name):
  58. """
  59. 在当前输出处标记锚点。 若已经存在 ``name`` 锚点,则先将旧锚点删除
  60. """
  61. inner_ancher_name = _get_anchor_id(name)
  62. send_msg('output_ctl', dict(set_anchor=inner_ancher_name))
  63. def clear_before(anchor):
  64. """清除 ``anchor`` 锚点之前输出的内容。
  65. ⚠️注意: 位于 ``anchor`` 锚点之前设置的锚点也会被清除
  66. """
  67. inner_ancher_name = _get_anchor_id(anchor)
  68. send_msg('output_ctl', dict(clear_before=inner_ancher_name))
  69. def clear_after(anchor):
  70. """清除 ``anchor`` 锚点之后输出的内容。
  71. ⚠️注意: 位于 ``anchor`` 锚点之后设置的锚点也会被清除
  72. """
  73. inner_ancher_name = _get_anchor_id(anchor)
  74. send_msg('output_ctl', dict(clear_after=inner_ancher_name))
  75. def clear_range(start_anchor, end_anchor):
  76. """
  77. 清除 ``start_anchor`` - ``end_ancher`` 锚点之间输出的内容.
  78. 若 ``start_anchor`` 或 ``end_ancher`` 不存在,则不进行任何操作。
  79. ⚠️注意: 在 ``start_anchor`` - ``end_ancher`` 之间设置的锚点也会被清除
  80. """
  81. inner_start_anchor_name = 'pywebio-anchor-%s' % start_anchor
  82. inner_end_ancher_name = 'pywebio-anchor-%s' % end_anchor
  83. send_msg('output_ctl', dict(clear_range=[inner_start_anchor_name, inner_end_ancher_name]))
  84. def remove(anchor):
  85. """将 ``anchor`` 锚点连同锚点处的内容移除"""
  86. inner_ancher_name = _get_anchor_id(anchor)
  87. send_msg('output_ctl', dict(remove=inner_ancher_name))
  88. def scroll_to(anchor, position=TOP):
  89. """将页面滚动到 ``anchor`` 锚点处
  90. :param str anchor: 锚点名
  91. :param str position: 将锚点置于屏幕可视区域的位置。可用值:
  92. * ``TOP`` : 滚动页面,让锚点位于屏幕可视区域顶部
  93. * ``MIDDLE`` : 滚动页面,让锚点位于屏幕可视区域中间
  94. * ``BOTTOM`` : 滚动页面,让锚点位于屏幕可视区域底部
  95. """
  96. inner_ancher_name = 'pywebio-anchor-%s' % anchor
  97. send_msg('output_ctl', dict(scroll_to=inner_ancher_name, position=position))
  98. def _get_output_spec(type, anchor=None, before=None, after=None, **other_spec):
  99. """
  100. 获取 ``output`` 指令的spec字段
  101. :param str type: 输出类型
  102. :param content: 输出内容
  103. :param str anchor: 为当前的输出内容标记锚点,若锚点已经存在,则将锚点处的内容替换为当前内容。
  104. :param str before: 在给定的锚点之前输出内容。若给定的锚点不存在,则不输出任何内容
  105. :param str after: 在给定的锚点之后输出内容。若给定的锚点不存在,则不输出任何内容。
  106. 注意: ``before`` 和 ``after`` 参数不可以同时使用
  107. :param other_spec: 额外的输出参数,值为None的参数不会包含到返回值中
  108. :return dict: ``output`` 指令的spec字段
  109. """
  110. assert not (before and after), "Parameter 'before' and 'after' cannot be specified at the same time"
  111. spec = dict(type=type)
  112. spec.update({k: v for k, v in other_spec.items() if v is not None})
  113. if anchor:
  114. spec['anchor'] = _get_anchor_id(anchor)
  115. if before:
  116. spec['before'] = _get_anchor_id(before)
  117. elif after:
  118. spec['after'] = _get_anchor_id(after)
  119. return spec
  120. def put_text(text, inline=False, anchor=None, before=None, after=None) -> OutputReturn:
  121. """
  122. 输出文本内容
  123. :param str text: 文本内容
  124. :param bool inline: 文本行末不换行。默认换行
  125. :param str anchor: 为当前的输出内容标记锚点,若锚点已经存在,则将锚点处的内容替换为当前内容。
  126. :param str before: 在给定的锚点之前输出内容。若给定的锚点不存在,则不输出任何内容
  127. :param str after: 在给定的锚点之后输出内容。若给定的锚点不存在,则不输出任何内容。
  128. 注意: ``before`` 和 ``after`` 参数不可以同时使用。
  129. 当 ``anchor`` 指定的锚点已经在页面上存在时,``before`` 和 ``after`` 参数将被忽略。
  130. """
  131. spec = _get_output_spec('text', content=str(text), inline=inline, anchor=anchor, before=before, after=after)
  132. return OutputReturn(spec)
  133. def put_html(html, anchor=None, before=None, after=None) -> OutputReturn:
  134. """
  135. 输出Html内容。
  136. 与支持通过Html输出内容到 `Jupyter Notebook <https://nbviewer.jupyter.org/github/ipython/ipython/blob/master/examples/IPython%20Kernel/Rich%20Output.ipynb#HTML>`_ 的库兼容。
  137. :param html: html字符串或 实现了 `IPython.display.HTML` 接口的类的实例
  138. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  139. """
  140. if hasattr(html, '__html__'):
  141. html = html.__html__()
  142. spec = _get_output_spec('html', content=html, anchor=anchor, before=before, after=after)
  143. return OutputReturn(spec)
  144. def put_code(content, langage='', anchor=None, before=None, after=None) -> OutputReturn:
  145. """
  146. 输出代码块
  147. :param str content: 代码内容
  148. :param str langage: 代码语言
  149. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  150. """
  151. code = "```%s\n%s\n```" % (langage, content)
  152. return put_markdown(code, anchor=anchor, before=before, after=after)
  153. def put_markdown(mdcontent, strip_indent=0, lstrip=False, anchor=None, before=None, after=None) -> OutputReturn:
  154. """
  155. 输出Markdown内容。
  156. :param str mdcontent: Markdown文本
  157. :param int strip_indent: 对于每一行,若前 ``strip_indent`` 个字符都为空格,则将其去除
  158. :param bool lstrip: 是否去除每一行开始的空白符
  159. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  160. 当在函数中使用Python的三引号语法输出多行内容时,为了排版美观可能会对Markdown文本进行缩进,
  161. 这时候,可以设置 ``strip_indent`` 或 ``lstrip`` 来防止Markdown错误解析(但不要同时使用 ``strip_indent`` 和 ``lstrip`` )::
  162. # 不使用strip_indent或lstrip
  163. def hello():
  164. put_markdown(r\""" # H1
  165. This is content.
  166. \""")
  167. # 使用lstrip
  168. def hello():
  169. put_markdown(r\""" # H1
  170. This is content.
  171. \""", lstrip=True)
  172. # 使用strip_indent
  173. def hello():
  174. put_markdown(r\""" # H1
  175. This is content.
  176. \""", strip_indent=4)
  177. """
  178. if strip_indent:
  179. lines = (
  180. i[strip_indent:] if (i[:strip_indent] == ' ' * strip_indent) else i
  181. for i in mdcontent.splitlines()
  182. )
  183. mdcontent = '\n'.join(lines)
  184. if lstrip:
  185. lines = (i.lstrip() for i in mdcontent.splitlines())
  186. mdcontent = '\n'.join(lines)
  187. spec = _get_output_spec('markdown', content=mdcontent, anchor=anchor, before=before, after=after)
  188. return OutputReturn(spec)
  189. def put_table(tdata, header=None, span=None, anchor=None, before=None, after=None) -> OutputReturn:
  190. """
  191. 输出表格
  192. :param list tdata: 表格数据。列表项可以为 ``list`` 或者 ``dict`` , 单元格的内容可以为字符串或其他输出函数的返回值,字符串内容显示时会被当作html。
  193. :param list header: 设定表头。
  194. 当 ``tdata`` 的列表项为 ``list`` 类型时,若省略 ``header`` 参数,则使用 ``tdata`` 的第一项作为表头。
  195. 当 ``tdata`` 为字典列表时,使用 ``header`` 指定表头顺序,不可省略。
  196. 此时, ``header`` 格式可以为 <字典键>列表 或者 ``(<显示文本>, <字典键>)`` 列表。
  197. :param dict span: 表格的跨行/跨列信息,格式为 ``{ (行id,列id):{"col": 跨列数, "row": 跨行数} }``
  198. 其中 ``行id`` 和 ``列id`` 为将表格转为二维数组后的需要跨行/列的单元格,二维数据包含表头,``id`` 从 0 开始记数。
  199. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  200. 使用示例::
  201. put_table([
  202. ['Name', 'Address'],
  203. ['City', 'Country'],
  204. ['Wang', 'Beijing', 'China'],
  205. ['Liu', 'New York', 'America'],
  206. ], span={(0,0):{"row":2}, (0,1):{"col":2}})
  207. put_table([
  208. ['Wang', 'M', 'China'],
  209. ['Liu', 'W', 'America'],
  210. ], header=['Name', 'Gender', 'Address'])
  211. put_table([
  212. {"Course":"OS", "Score": "80"},
  213. {"Course":"DB", "Score": "93"},
  214. ], header=["Course", "Score"]) # or header=[("课程", "Course"), ("得分" ,"Score")]
  215. """
  216. # Change ``dict`` row table to list row table
  217. if tdata and isinstance(tdata[0], dict):
  218. if isinstance(header[0], (list, tuple)):
  219. header_ = [h[0] for h in header]
  220. order = [h[-1] for h in header]
  221. else:
  222. header_ = order = header
  223. tdata = [
  224. [row.get(k, '') for k in order]
  225. for row in tdata
  226. ]
  227. header = header_
  228. if header:
  229. tdata = [header, *tdata]
  230. span = span or {}
  231. span = {('%s,%s' % row_col): val for row_col, val in span.items()}
  232. spec = _get_output_spec('table', data=tdata, span=span, anchor=anchor, before=before, after=after)
  233. return OutputReturn(spec)
  234. def _format_button(buttons):
  235. """
  236. 格式化按钮参数
  237. :param buttons: button列表, button可用形式:
  238. {label:, value:, }
  239. (label, value, )
  240. value 单值,label等于value
  241. :return: [{value:, label:, }, ...]
  242. """
  243. btns = []
  244. for btn in buttons:
  245. if isinstance(btn, Mapping):
  246. assert 'value' in btn and 'label' in btn, 'actions item must have value and label key'
  247. elif isinstance(btn, (list, tuple)):
  248. assert len(btn) == 2, 'actions item format error'
  249. btn = dict(zip(('label', 'value'), btn))
  250. else:
  251. btn = dict(value=btn, label=btn)
  252. btns.append(btn)
  253. return btns
  254. def table_cell_buttons(buttons, onclick, **callback_options) -> str:
  255. """
  256. 在表格中显示一组按钮
  257. :param str buttons, onclick, save: 与 `put_buttons` 函数的同名参数含义一致
  258. .. _table_cell_buttons-code-sample:
  259. 使用示例::
  260. from functools import partial
  261. def edit_row(choice, row):
  262. put_text("You click %s button at row %s" % (choice, row))
  263. put_table([
  264. ['Idx', 'Actions'],
  265. ['1', table_cell_buttons(['edit', 'delete'], onclick=partial(edit_row, row=1))],
  266. ['2', table_cell_buttons(['edit', 'delete'], onclick=partial(edit_row, row=2))],
  267. ['3', table_cell_buttons(['edit', 'delete'], onclick=partial(edit_row, row=3))],
  268. ])
  269. """
  270. btns = _format_button(buttons)
  271. callback_id = output_register_callback(onclick, **callback_options)
  272. tpl = '<button type="button" value="{value}" class="btn btn-primary btn-sm" ' \
  273. 'onclick="WebIO.DisplayAreaButtonOnClick(this, \'%s\')">{label}</button>' % callback_id
  274. btns_html = [tpl.format(**b) for b in btns]
  275. return ' '.join(btns_html)
  276. def put_buttons(buttons, onclick, small=None, anchor=None, before=None, after=None,
  277. **callback_options) -> OutputReturn:
  278. """
  279. 输出一组按钮
  280. :param list buttons: 按钮列表。列表项的可用形式有:
  281. * dict: ``{label:选项标签, value:选项值}``
  282. * tuple or list: ``(label, value)``
  283. * 单值: 此时label和value使用相同的值
  284. :type onclick: Callable or Coroutine
  285. :param onclick: 按钮点击回调函数. ``onclick`` 可以是普通函数或者协程函数.
  286. 函数签名为 ``onclick(btn_value)``.
  287. 当按钮组中的按钮被点击时,``onclick`` 被调用,并传入被点击的按钮的 ``value`` 值。
  288. 可以使用 ``functools.partial`` 来在 ``onclick`` 中保存更多上下文信息,见 `table_cell_buttons` :ref:`代码示例 <table_cell_buttons-code-sample>` 。
  289. :param bool small: 是否显示小号按钮,默认为False
  290. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  291. :param callback_options: 回调函数的其他参数。根据选用的 session 实现有不同参数
  292. CoroutineBasedSession 实现
  293. * mutex_mode: 互斥模式。默认为 ``False`` 。若为 ``True`` ,则在运行回调函数过程中,无法响应当前按钮组的新点击事件,仅当 ``onclick`` 为协程函数时有效
  294. ThreadBasedSession 实现
  295. * serial_mode: 串行模式模式。默认为 ``False`` 。若为 ``True`` ,则运行当前点击事件时,其他所有新的点击事件都将被排队等待当前点击事件时运行完成。
  296. 不开启 ``serial_mode`` 时,ThreadBasedSession 在新线程中执行回调函数。所以如果回调函数运行时间很短,
  297. 可以关闭 ``serial_mode`` 来提高性能。
  298. """
  299. btns = _format_button(buttons)
  300. callback_id = output_register_callback(onclick, **callback_options)
  301. spec = _get_output_spec('buttons', callback_id=callback_id, buttons=btns, small=small, anchor=anchor, before=before,
  302. after=after)
  303. def on_embed(spec):
  304. spec.setdefault('small', True)
  305. return spec
  306. return OutputReturn(spec, on_embed=on_embed)
  307. def put_image(content, format=None, title='', width=None, height=None, anchor=None, before=None,
  308. after=None) -> OutputReturn:
  309. """输出图片。
  310. :param content: 文件内容. 类型为 bytes-like object 或者为 ``PIL.Image.Image`` 实例
  311. :param str title: 图片描述
  312. :param str width: 图像的宽度,单位是CSS像素(数字px)或者百分比(数字%)。
  313. :param str height: 图像的高度,单位是CSS像素(数字px)或者百分比(数字%)。可以只指定 width 和 height 中的一个值,浏览器会根据原始图像进行缩放。
  314. :param str format: 图片格式。如 ``png`` , ``jpeg`` , ``gif`` 等
  315. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  316. """
  317. if isinstance(content, PILImage):
  318. format = content.format
  319. imgByteArr = io.BytesIO()
  320. content.save(imgByteArr, format=format)
  321. content = imgByteArr.getvalue()
  322. format = '' if format is None else ('image/%s' % format)
  323. width = 'width="%s"' % width if width is not None else ''
  324. height = 'height="%s"' % height if height is not None else ''
  325. b64content = b64encode(content).decode('ascii')
  326. html = r'<img src="data:{format};base64, {b64content}" ' \
  327. r'alt="{title}" {width} {height}/>'.format(format=format, b64content=b64content,
  328. title=title, height=height, width=width)
  329. return put_html(html, anchor=anchor, before=before, after=after)
  330. def put_file(name, content, anchor=None, before=None, after=None) -> OutputReturn:
  331. """输出文件。
  332. 在浏览器上的显示为一个以文件名为名的链接,点击链接后浏览器自动下载文件。
  333. :param str name: 文件名
  334. :param content: 文件内容. 类型为 bytes-like object
  335. :param str anchor, before, after: 与 `put_text` 函数的同名参数含义一致
  336. """
  337. content = b64encode(content).decode('ascii')
  338. spec = _get_output_spec('file', name=name, content=content, anchor=anchor, before=before, after=after)
  339. return OutputReturn(spec)