pywebio.output — 输出模块

本模块提供了一系列函数来输出不同形式的内容到用户浏览器,并支持灵活的输出控制。

函数清单

下表为PyWebIO提供的输出相关的函数。
其中标记有 * 的函数表示其支持接收 put_xxx 调用作为参数。
标记有 的函数表示其支持作为上下文管理器使用。

函数

简介

输出域Scope

put_scope

创建一个新的scope.

use_scope

进入输出域

get_scope

获取当前正在使用的输出域

clear

清空scope内容

remove

移除Scope

scroll_to

将页面滚动到 scope Scope处

内容输出

put_text

输出文本

put_markdown

输出Markdown

输出通知消息

put_html

输出Html

put_link

输出链接

put_progressbar

Output a progress bar

put_loading

输出加载提示

put_code

输出代码块

put_table*

输出表格

Output and update data table

输出按钮,并绑定点击事件

put_image

输出图片

put_file

显示一个文件下载链接

put_tabs*

输出横向标签栏Tabs

put_collapse*†

输出可折叠的内容

put_scrollable*†

固定高度内容输出区域
内容超出则显示滚动条
.

put_widget*

输出自定义的控件

其他交互

toast

显示一条通知消息

popup*†

显示弹窗

close_popup

关闭正在显示的弹窗

布局与样式

put_row*†

使用行布局输出内容

put_column*†

使用列布局输出内容

put_grid*

使用网格布局输出内容

span

put_table()put_grid() 中设置内容跨单元格

style*

自定义输出内容的css样式

输出域Scope

pywebio.output.put_scope(name: str, content: Output | List[Output] = [], scope: str = None, position: int = -1) Output[源代码]

输出一个输出域

参数:
  • name (str)

  • content (list/put_xxx()) – 输出域里的初始内容,可以为 put_xxx() 调用或其列表。

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

pywebio.output.use_scope(name=None, clear=False)[源代码]

scope的上下文管理器和装饰器。用于创建一个新的输出域并进入,或进入一个已经存在的输出域。

参见 用户手册-use_scope()

参数:
  • name (str) – scope名. 若为None则生成一个全局唯一的scope名.(以上下文管理器形式的调用时,上下文管理器会返回scope名)

  • clear (bool) – 在进入scope前是否要清除scope里的内容

Usage:

with use_scope(...) as scope_name:
    put_xxx()

@use_scope(...)
def app():
    put_xxx()
pywebio.output.get_scope(stack_idx: int = -1)[源代码]

获取当前运行时scope栈中的scope名

参数:

stack_idx (int) – 当前运行时的scope栈索引。-1表示当前scope,-2表示进入当前scope前的scope,依次类推;0表示 ROOT scope

返回:

返回Scope栈中对应索引的scope名,索引错误时返回None

pywebio.output.clear(scope: str | None = None)[源代码]

清空scope内容

参数:

scope (str) – 目标scope名。默认为当前scope

pywebio.output.remove(scope: str | None = None)[源代码]

移除Scope

参数:

scope (str) – 目标scope名。默认为当前scope

pywebio.output.scroll_to(scope: str | None = None, position: str = 'top')[源代码]

将页面滚动到 scope Scope处

参数:
  • scope (str) – Target scope. Default is the current scope.

  • position (str) –

    将Scope置于屏幕可视区域的位置。可用值:

    • 'top' : 滚动页面,让Scope位于屏幕可视区域顶部

    • 'middle' : 滚动页面,让Scope位于屏幕可视区域中间

    • 'bottom' : 滚动页面,让Scope位于屏幕可视区域底部

内容输出

Scope related parameters of output function

输出函数默认将内容输出到“当前scope”,“当前scope”可由 use_scope() 设置。

另外,所有输入函数都支持使用 scope 参数来指定输出的目的scope:

with use_scope('scope3'):
    put_text('text1 in scope3')   # output to current scope: scope3
    put_text('text in ROOT scope', scope='ROOT')   # output to ROOT Scope

put_text('text2 in scope3', scope='scope3')   # output to scope3

以上代码运行结果如下:

text1 in scope3
text2 in scope3
text in ROOT scope

一个scope可以包含多个输出项,输出函数的默认行为是将内容追加到目标scope中。可以使用输出函数的 position 参数来指定输出内容在目标scope中的插入位置。

一个Scope中各次输出的元素具有像数组一样的索引,最前面的编号为0,以此往后递增加一;同样可以使用负数对Scope中的元素进行索引,-1表示最后面的元素,-2表示次后面的元素……

position 参数类型为整形, position>=0 时表示输出内容到目标Scope的第position号元素的前面; position<0 时表示输出内容到目标Scope第position号元素之后:

with use_scope('scope1'):
    put_text('A')
    put_text('B', position=0)   # insert B before A -> B A
    put_text('C', position=-2)  # insert C after B -> B C A
    put_text('D', position=1)   # insert D before C B -> B D C A

Output functions

pywebio.output.put_text(*texts: Any, sep: str = ' ', inline: bool = False, scope: str | None = None, position: int = -1) Output[源代码]

输出文本

参数:
  • texts – 要输出的内容。类型可以为任意对象,对非字符串对象会应用 str() 函数作为输出值。

  • sep (str) – 输出分隔符

  • inline (bool) – 将文本作为行内元素(连续输出的文本显示在相同的段落中)。默认每次输出的文本都作为一个独立的段落

  • scope (str) –

    内容输出的目标scope,若scope不存在,则不进行任何输出操作。

    可以直接指定目标Scope名,或者使用int通过索引Scope栈来确定Scope

  • position (int) – 在scope中输出的位置。

参数 scopeposition 的更多使用说明参见 用户手册

pywebio.output.put_markdown(mdcontent: str, lstrip: bool = True, options: Dict[str, str | bool] | None = None, sanitize: bool = True, scope: str | None = None, position: int = -1, **kwargs) Output[源代码]

输出Markdown

参数:
  • mdcontent (str) – Markdown文本

  • lstrip (bool) – 是否自动移除 mdcontent 每一行的前导空白锁进

  • options (dict) – 解析Markdown时的配置参数。 PyWebIO使用 marked 解析Markdown, 可配置项参见: https://marked.js.org/using_advanced#options (仅支持配置string和boolean类型的项)

  • sanitize (bool) – 是否使用 DOMPurify 对内容进行过滤来防止XSS攻击。

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

当使用python三引号语法在函数中输出多行Markdown内容时,你可以缩进Markdown内容来使代码保持美观。PyWebIO会智能地移除Markdown中的缩进:

# good code format
def hello():
    put_markdown(r""" # H1
    This is content.
    """)

在 1.5 版本发生变更: Enable lstrip by default. Deprecate strip_indent.

pywebio.output.put_info(*contents, closable=False, scope=None, position=-1) Output:[源代码]
pywebio.output.put_success(*contents, closable=False, scope=None, position=-1) Output:[源代码]
pywebio.output.put_warning(*contents, closable=False, scope=None, position=-1) Output:[源代码]
pywebio.output.put_error(*contents, closable=False, scope=None, position=-1) Output:[源代码]

输出通知消息

参数:
  • contents – 消息内容. 元素为 put_xxx() 调用,其他类型会被转换成 put_text(content)

  • closable (bool) – 是否在消息框右侧展示一个关闭按钮。

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

Added in version 1.2.

pywebio.output.put_html(html: Any, sanitize: bool = False, scope: str | None = None, position: int = -1) Output[源代码]

输出Html内容

参数:
  • html – html字符串

  • sanitize (bool) – 是否使用 DOMPurify 对内容进行过滤来防止XSS攻击。

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

输出链接到其他网页或PyWebIO App的超链接

参数:
  • name (str) – 链接名称

  • url (str) – 链接到的页面地址

  • app (str) – 链接到的PyWebIO应用名。参见 Server模式

  • new_window (bool) – 是否在新窗口打开链接

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

urlapp 参数必须指定一个但不可以同时指定

pywebio.output.put_progressbar(name: str, init: float = 0, label: str | None = None, auto_close: bool = False, scope: str | None = None, position: int = -1) Output[源代码]

Output a progress bar

参数:
  • name (str) – 进度条名称,为进度条的唯一标识

  • init (float) – 进度条初始值. 进度条的值在 0 ~ 1 之间

  • label (str) – The label of progress bar. The default is the percentage value of the current progress.

  • auto_close (bool) – 是否在进度完成后关闭进度条

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

Example:

import time

put_progressbar('bar');
for i in range(1, 11):
    set_progressbar('bar', i / 10)
    time.sleep(0.1)

参见

use set_progressbar() to set the progress of progress bar

pywebio.output.set_progressbar(name: str, value: float, label: str | None = None)[源代码]

设置进度条进度

参数:
  • name (str) – 设置进度条进度

  • value (float) – 进度条的值. 范围在 0 ~ 1 之间

  • label (str) – The label of progress bar. The default is the percentage value of the current progress.

See also: put_progressbar()

pywebio.output.put_loading(shape: str = 'border', color: str = 'dark', scope: str | None = None, position: int = -1) Output[源代码]

输出加载提示

参数:
  • shape (str) – 加载提示的形状, 可选值: 'border' (默认,旋转的圆环)、 'grow' (大小渐变的圆点)

  • color (str) – 加载提示的颜色, 可选值: 'primary''secondary''success''danger''warning''info''light''dark' (默认)

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

put_loading() 支持直接调用和上下文管理器:

for shape in ('border', 'grow'):
    for color in ('primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'):
        put_text(shape, color)
        put_loading(shape=shape, color=color)

# The loading prompt and the output inside the context will disappear
# automatically when the context block exits.
with put_loading():
    put_text("Start waiting...")
    time.sleep(3)  # Some time-consuming operations
put_text("The answer of the universe is 42")

# using style() to set the size of the loading prompt
put_loading().style('width:4rem; height:4rem')

在 1.8 版本发生变更: when use put_loading() as context manager, the output inside the context will also been removed after the context block exits.

pywebio.output.put_code(content: str, language: str = '', rows: int | None = None, scope: str | None = None, position: int = -1) Output[源代码]

输出代码块

参数:
  • content (str) – 代码内容

  • language (str) – 代码语言

  • rows (int) – 代码块最多可显示的文本行数,默认不限制。内容超出时会使用滚动条。

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

pywebio.output.put_table(tdata: List[List | Dict], header: List[str | Tuple[Any, str]] = None, scope: str = None, position: int = -1) Output[源代码]

输出表格

参数:
  • tdata (list) – 表格数据。列表项可以为 list 或者 dict , 单元格的内容可以为字符串或 put_xxx 类型的输出函数。 数组项可以使用 span() 函数来设定单元格跨度。

  • header (list) –

    表头。当 tdata 的列表项为 list 类型时,若省略 header 参数,则使用 tdata 的第一项作为表头。表头项可以使用 span() 函数来设定单元格跨度。

    When tdata is list of dict, header can be used to specify the order of table headers. In this case, the header can be a list of dict key or a list of (<label>, <dict key>).

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

Example:

# 'Name' cell across 2 rows, 'Address' cell across 2 columns
put_table([
    [span('Name',row=2), span('Address', col=2)],
    ['City', 'Country'],
    ['Wang', 'Beijing', 'China'],
    ['Liu', 'New York', 'America'],
])

# Use `put_xxx()` in `put_table()`
put_table([
    ['Type', 'Content'],
    ['html', put_html('X<sup>2</sup>')],
    ['text', '<hr/>'],
    ['buttons', put_buttons(['A', 'B'], onclick=...)],  
    ['markdown', put_markdown('`Awesome PyWebIO!`')],
    ['file', put_file('hello.text', b'hello world')],
    ['table', put_table([['A', 'B'], ['C', 'D']])]
])

# Set table header
put_table([
    ['Wang', 'M', 'China'],
    ['Liu', 'W', 'America'],
], header=['Name', 'Gender', 'Address'])

# When ``tdata`` is list of dict
put_table([
    {"Course":"OS", "Score": "80"},
    {"Course":"DB", "Score": "93"},
], header=["Course", "Score"])  # or header=[(put_markdown("*Course*"), "Course"), (put_markdown("*Score*") ,"Score")]

Added in version 0.3: 单元格的内容支持 put_xxx 类型的输出函数

pywebio.output.span(content: str | Output, row: int = 1, col: int = 1)[源代码]

用于在 put_table()put_grid() 中设置内容跨单元格

参数:
  • content – 单元格内容。可以为字符串或 put_xxx() 调用。

  • row (int) – 竖直方向跨度, 即:跨行的数目

  • col (int) – 水平方向跨度, 即:跨列的数目

Example:

put_table([
    ['C'],
    [span('E', col=2)],  # 'E' across 2 columns
], header=[span('A', row=2), 'B'])  # 'A' across 2 rows

put_grid([
    [put_text('A'), put_text('B')],
    [span(put_text('A'), col=2)],  # 'A' across 2 columns
])
pywebio.output.put_buttons(buttons: List[Dict[str, Any] | Tuple[str, Any] | List | str], onclick: Callable[[Any], None] | Sequence[Callable[[], None]], small: bool | None = None, link_style: bool = False, outline: bool = False, group: bool = False, scope: str | None = None, position: int = -1, **callback_options) Output[源代码]

输出一组按钮,并绑定点击事件

参数:
  • buttons (list) –

    按钮列表。列表项的可用形式有:

    • dict:

      {
          "label":(str) 按钮标签,,
          "value":(str) 按钮值,
          "color":(str, optional) 按钮颜色,
          "disabled":(bool, optional) 按钮时否被禁用
      }
      
    • tuple or list: (label, value)

    • 单值: 此时label和value使用相同的值

    其中, value 可以为任意对象。使用dict类型的列表项时,支持使用 color key设置按钮颜色,可选值为 primarysecondarysuccessdangerwarninginfolightdark .

    Example:

    put_buttons([dict(label='success', value='s', color='success')], onclick=...)  
    

  • onclick (callable / list) –

    按钮点击回调函数. onclick 可以是函数或者函数组成的列表.

    onclick 为函数时, 签名为 onclick(btn_value). btn_value 为被点击的按钮的 value

    onclick 为列表时,列表内函数的签名为 func(). 此时,回调函数与 buttons 一一对应

    Tip: 可以使用 functools.partial 来在 onclick 中保存更多上下文信息.

    Note: 当使用 基于协程的会话实现 时,回调函数可以为协程函数.

  • small (bool) – 是否使用小号按钮,默认为False

  • link_style (bool) – 是否将按钮显示为链接样式,默认为False

  • outline (bool) – 是否将按钮显示为镂空样式,默认为False

  • group (bool) – 是否将按钮合并在一起,默认为False

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

  • callback_options

    回调函数的其他参数。根据选用的 session 实现有不同参数

    CoroutineBasedSession 实现
    • mutex_mode: 互斥模式。默认为 False 。若为 True ,则在运行回调函数过程中,无法响应当前按钮组的新点击事件,仅当 onclick 为协程函数时有效

    ThreadBasedSession 实现
    • serial_mode: 串行模式模式。默认为 False ,此时每次触发回调,回调函数会在新线程中立即执行。

    开启serial_mode后,该按钮的回调会在会话内的一个固定线程内串行执行,且其他所有新的点击事件的回调(包括 serial_mode=False 的回调)都将排队等待当前点击事件运行完成。如果回调函数运行时间很短,可以开启 serial_mode 来提高性能。

Example:

from functools import partial

def row_action(choice, id):
    put_text("You click %s button with id: %s" % (choice, id))

put_buttons(['edit', 'delete'], onclick=partial(row_action, id=1))

def edit():
    put_text("You click edit button")
def delete():
    put_text("You click delete button")

put_buttons(['edit', 'delete'], onclick=[edit, delete])

在 1.5 版本发生变更: Add disabled button support. The value of button can be any object.

pywebio.output.put_button(label: str, onclick: Callable[[], None], color: str | None = None, small: bool | None = None, link_style: bool = False, outline: bool = False, disabled: bool = False, scope: str | None = None, position: int = -1) Output[源代码]

输出一个按钮,并绑定点击事件

参数:
  • label (str) – Button label

  • onclick (callable) – 按钮点击回调函数

  • color (str) – 按钮颜色。可选值为 primarysecondarysuccessdangerwarninginfolightdark .

  • disabled (bool) – Whether the button is disabled

  • position (- small, link_style, outline, scope,) – 与 put_buttons() 函数的同名参数含义一致

Example:

put_button("click me", onclick=lambda: toast("Clicked"), color='success', outline=True)

Added in version 1.4.

在 1.5 版本发生变更: add disabled parameter

pywebio.output.put_image(src: str | bytes | Image, format: str | None = None, title: str = '', width: str | None = None, height: str | None = None, scope: str | None = None, position: int = -1) Output[源代码]

输出图片

参数:
  • src – 图片内容. 可以为: 字符串类型的URL, bytes-like object 表示的图片二进制内容, PIL.Image.Image 实例

  • title (str) – 图片描述

  • width (str) – 图像的宽度,可以是CSS像素(数字px)或者百分比(数字%)。

  • height (str) – 图像的高度,可以是CSS像素(数字px)或者百分比(数字%)。可以只指定 width 和 height 中的一个值,浏览器会根据原始图像进行缩放。

  • format (str) – 图片格式,非必须。如 png , jpeg , gif 等, 仅在 src 为非URL时有效

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

Example:

img = open('/path/to/some/image.png', 'rb').read()  
put_image(img, width='50px')

put_image('https://www.python.org/static/img/python-logo.png')
pywebio.output.put_file(name: str, content: bytes, label: str | None = None, scope: str | None = None, position: int = -1) Output[源代码]

显示一个文件下载链接

在浏览器上的显示为一个以文件名为名的链接,点击链接后浏览器自动下载文件。

参数:
  • name (str) – 下载保存为的文件名

  • content – 文件内容. 类型为 bytes-like object

  • label (str) – 下载链接的显示文本,默认和文件名相同

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

Example:

content = open('./some-file', 'rb').read()  
put_file('hello-world.txt', content, 'download me')
pywebio.output.put_tabs(tabs: List[Dict[str, Any]], scope: str = None, position: int = -1) Output[源代码]

输出横向标签栏Tabs

参数:
  • tabs (list) – 标签列表,列表项为一个 dict: {"title": "Title", "content": ...} ,其中 content 表示标签内容,可以为字符串、 put_xxx() 调用或由它们组成的列表。

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

put_tabs([
    {'title': 'Text', 'content': 'Hello world'},
    {'title': 'Markdown', 'content': put_markdown('~~Strikethrough~~')},
    {'title': 'More content', 'content': [
        put_table([
            ['Commodity', 'Price'],
            ['Apple', '5.5'],
            ['Banana', '7'],
        ]),
        put_link('pywebio', 'https://github.com/wang0618/PyWebIO')
    ]},
])

Added in version 1.3.

pywebio.output.put_collapse(title: str, content: str | Output | List[str | Output] = [], open: bool = False, scope: str = None, position: int = -1) Output[源代码]

输出可折叠的内容

参数:
  • title (str) – 内容标题

  • content (list/str/put_xxx()) – 内容可以为字符串或 put_xxx 类输出函数的返回值,或者由它们组成的列表。

  • open (bool) – 是否默认展开折叠内容。默认不展开内容

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

Example:

put_collapse('Collapse title', [
    'text',
    put_markdown('~~Strikethrough~~'),
    put_table([
        ['Commodity', 'Price'],
        ['Apple', '5.5'],
    ])
], open=True)

put_collapse('Large text', 'Awesome PyWebIO! '*30)
pywebio.output.put_scrollable(content: str | Output | List[str | Output] = [], height: int | Tuple[int, int] = 400, keep_bottom: bool = False, border: bool = True, scope: str = None, position: int = -1, **kwargs) Output[源代码]

固定高度内容输出区域,内容超出则显示滚动条

参数:
  • content (list/str/put_xxx()) – 内容可以为字符串或 put_xxx 类输出函数的返回值,或者由它们组成的列表。

  • height (int/tuple) – 区域的高度(像素),内容超出此高度则使用滚动条。可以传入 (min_height, max_height) 来表示高度的范围,比如 (100, 200) 表示区域高度最小100像素、最高200像素。若不想限制高度,则传入 None

  • keep_bottom (bool) – Whether to keep the content area scrolled to the bottom when updated.

  • border (bool) – 是否显示边框

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

Example:

import time

put_scrollable(put_scope('scrollable'), height=200, keep_bottom=True)
put_text("You can click the area to prevent auto scroll.", scope='scrollable')

while 1:
    put_text(time.time(), scope='scrollable')
    time.sleep(0.5)

在 1.1 版本发生变更: 添加 height 参数,移除 max_height 参数;添加 keep_bottom 参数

在 1.5 版本发生变更: remove horizon_scroll parameter

pywebio.output.put_datatable(records: Sequence[Mapping], actions: Sequence[Tuple[str, Callable[[str | int | List[str | int]], None]]] | None = None, onselect: Callable[[str | int | List[str | int]], None] | None = None, multiple_select=False, id_field: str | None = None, height: str | int = 600, theme: Literal['alpine', 'alpine-dark', 'balham', 'balham-dark', 'material'] = 'balham', cell_content_bar=True, instance_id='', column_order: Sequence[str] | Mapping | None = None, column_args: Mapping[str | Tuple, Mapping] | None = None, grid_args: Mapping[str, Any] | None = None, enterprise_key='', scope: str | None = None, position: int = -1) Output[源代码]

Output a datatable.

Compared with put_table(), put_datatable() is more suitable for displaying large amounts of data (both data fields and data entries), while put_table() is more suitable for displaying diverse data types (pictures, buttons, etc.) in cells.

This widget is powered by the awesome ag-grid library.

参数:
  • records (list[dict]) – data of rows, each row is a python dict, which can be nested.

  • actions (list) – actions for selected row(s), they will be shown as buttons when row is selected. The format of the action item: (button_label:str, on_click:callable). Specifically, None item is allowed, which will be rendered as a separator. The on_click callback receives the selected row ID as parameter.

  • onselect (callable) – callback when row is selected, receives the selected row ID as parameter.

  • multiple_select (bool) – whether multiple rows can be selected. When enabled, the on_click callback in actions and the onselect callback will receive ID list of selected rows as parameter.

  • id_field (str/tuple) –

    row ID field, that is, the key of the row dict to uniquely identifies a row. When not provide, the datatable will use the index in records to assign row ID.

    Notes when the row record is nested dict

    To specify the ID field of a nested dict, use a tuple to specify the path of the ID field. For example, if the row record is in {'a': {'b': ...}} format, you can use id_field=('a', 'b') to set 'b' column as the ID field.

  • height (int/str) – widget height. When pass int type, the unit is pixel, when pass str type, you can specify any valid CSS height value. In particular, you can use 'auto' to make the datatable auto-size it’s height to fit the content.

  • theme (str) – datatable theme. Available themes are: 'balham' (default), 'alpine', 'alpine-dark', 'balham-dark', 'material'. You can preview the themes in ag-grid official example.

  • cell_content_bar (bool) – whether to add a text bar to datatable to show the content of current focused cell. Default is True.

  • instance_id (str) – Assign a unique ID to the datatable, so that you can refer this datatable in datatable_update(), datatable_insert() and datatable_remove() functions.

  • column_order (list) –

    column order, the order of the column names in the list will be used as the column order. If not provided, the column order will be the same as the order of the keys in the first row of records. When provided, the column not in the list will not be shown. Note that column_order must be specified when records is empty.

    Notes when the row record is nested dict

    Since the dict in python is ordered after py3.7, you can use dict to specify the column order when the row record is nested dict. For example:

    column_order = {'a': {'b': {'c': None, 'd': None}, 'e': None}, 'f': None}
    

  • column_args

    column properties. Dict type, the key is str to specify the column field, the value is ag-grid column properties in dict.

    Notes when the row record is nested dict

    Given the row record is in this format:

    {
        "a": {"b": ..., "c": ...},
        "b": ...,
        "c": ...
    }
    

    When you set column_args={"b": settings}, the column settings will be applied to the column a.b and b. Use tuple as key to specify the nested key path, for example, column_args={("a", "b"): settings} will only apply the settings to column a.b.

  • grid_args – ag-grid grid options. Refer ag-grid doc - grid options for more information.

  • enterprise_key (str) – ag-grid enterprise license key. When not provided, will use the ag-grid community version.

The ag-grid library is so powerful, and you can use the column_args and grid_args parameters to achieve high customization.

Example of put_datatable():

import urllib.request
import json

with urllib.request.urlopen('https://fakerapi.it/api/v1/persons?_quantity=30') as f:
    data = json.load(f)['data']

put_datatable(
    data,
    actions=[
        ("Edit Email", lambda row_id: datatable_update('user', input("Email"), row_id, "email")),
        ("Insert a Row", lambda row_id: datatable_insert('user', data[0], row_id)),
        None,  # separator
        ("Delete", lambda row_id: datatable_remove('user', row_id)),
    ],
    onselect=lambda row_id: toast(f'Selected row: {row_id}'),
    instance_id='user'
)
Advanced topic: Interact with ag-grid in Javascript

The ag-grid instance can be accessed with JS global variable ag_grid_${instance_id}_promise:

ag_grid_xxx_promise.then(function(gridOptions) {
    // gridOptions is the ag-grid gridOptions object
    gridOptions.columnApi.autoSizeAllColumns();
});

To pass JS functions as value of column_args or grid_args, you can use JSFunction object:

pywebio.output.JSFunction([param1, ][param2, ]..., [param n, ]body)[源代码]

Example:

put_datatable(..., grid_args=dict(sortChanged=JSFunction("event", "console.log(event.source)")))

Since the ag-grid don’t native support nested dict as row record, PyWebIO will internally flatten the nested dict before passing to ag-grid. So when you access or modify data in ag-grid directly, you need to use the following functions to help you convert the data:

  • gridOptions.flatten_row(nested_dict_record): flatten the nested dict record to a flat dict record

  • gridOptions.path2field(field_path_array): convert the field path array to field name used in ag-grid

  • gridOptions.field2path(ag_grid_column_field_name): convert the field name back to field path array

The implement of datatable_update(), datatable_insert and datatable_remove functions are good examples to show how to interact with ag-grid in Javascript.

pywebio.output.datatable_update(instance_id: str, data: Any, row_id: str | int | None = None, field: str | List[str] | Tuple[str] | None = None)[源代码]

Update the whole data / a row / a cell of the datatable.

To use datatable_update(), you need to specify the instance_id parameter when calling put_datatable().

When row_id and field is not specified (datatable_update(instance_id, data)), the whole data of datatable will be updated, in this case, the data parameter should be a list of dict (same as records in put_datatable()).

To update a row, specify the row_id parameter and pass the row data in dict to data parameter (datatable_update(instance_id, data, row_id)). See id_field of put_datatable() for more info of row_id.

To update a cell, specify the row_id and field parameters, in this case, the data parameter should be the cell value To update a row, specify the row_id parameter and pass the row data in dict to data parameter (datatable_update(instance_id, data, row_id, field)). The field can be a tuple to indicate nested key path.

pywebio.output.datatable_insert(instance_id: str, records: List, row_id=None)[源代码]

Insert rows to datatable.

参数:
  • instance_id (str) – Datatable instance id (i.e., the instance_id parameter when calling put_datatable())

  • records (dict/list[dict]) – row record or row record list to insert

  • row_id (str/int) – row id to insert before, if not specified, insert to the end

Note:

When use id_field=None (default) in put_datatable(), the row id of new inserted rows will auto increase from the last max row id.

pywebio.output.datatable_remove(instance_id: str, row_ids: List)[源代码]

Remove rows from datatable.

参数:
  • instance_id (str) – Datatable instance id (i.e., the instance_id parameter when calling put_datatable())

  • row_ids (int/str/list) – row id or row id list to remove

pywebio.output.put_widget(template: str, data: Dict[str, Any], scope: str = None, position: int = -1) Output[源代码]

输出自定义的控件

参数:
  • template – html模版,使用 mustache.js 语法

  • data (dict) –

    渲染模版使用的数据.

    数据可以包含输出函数( put_xxx() )的返回值, 可以使用 pywebio_output_parse 函数来解析 put_xxx() 内容;对于字符串输入, pywebio_output_parse 会将解析成文本.

    ⚠️:使用 pywebio_output_parse 函数时,需要关闭mustache的html转义: {{& pywebio_output_parse}} , 参见下文示例.

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

Example:

tpl = '''
<details {{#open}}open{{/open}}>
    <summary>{{title}}</summary>
    {{#contents}}
        {{& pywebio_output_parse}}
    {{/contents}}
</details>
'''

put_widget(tpl, {
    "open": True,
    "title": 'More content',
    "contents": [
        'text',
        put_markdown('~~Strikethrough~~'),
        put_table([
            ['Commodity', 'Price'],
            ['Apple', '5.5'],
            ['Banana', '7'],
        ])
    ]
})

其他交互

pywebio.output.toast(content: str, duration: float = 2, position: str = 'center', color: str = 'info', onclick: Callable[[], None] | None = None)[源代码]

显示一条通知消息

参数:
  • content (str) – 通知内容

  • duration (float) – 通知显示持续的时间,单位为秒。 0 表示不自动关闭(此时消息旁会显示一个关闭图标,用户可以手动关闭消息)

  • position (str) – 通知消息显示的位置,可以为 'left' / 'center' / 'right'

  • color (str) – 通知消息的背景颜色,可以为 'info' / 'error' / 'warn' / 'success' 或以 '#' 开始的十六进制颜色值

  • onclick (callable) –

    点击通知消息时的回调函数,回调函数不接受任何参数。

    Note: 当使用 基于协程的会话实现 时,回调函数可以为协程函数.

Example:

def show_msg():
    put_text("You clicked the notification.")

toast('New messages', position='right', color='#2188ff', duration=0, onclick=show_msg)
pywebio.output.popup(title: str, content: str | Output | List[str | Output] = None, size: str = 'normal', implicit_close: bool = True, closable: bool = True)[源代码]

显示弹窗

⚠️: PyWebIO不允许同时显示多个弹窗,在显示新弹窗前,会自动关闭页面上存在的弹窗。可以使用 close_popup() 主动关闭弹窗

参数:
  • title (str) – 弹窗标题

  • content (list/str/put_xxx()) – The content of the popup. Can be a string, the put_xxx() calls, or a list of them.

  • size (str) – 弹窗窗口大小,可选值: 'large', 'normal' and 'small'.

  • implicit_close (bool) – 是否可以通过点击弹窗外的内容或按下 Esc 键来关闭弹窗,默认为 False

  • closable (bool) – 是否可由用户关闭弹窗. 默认情况下,用户可以通过点击弹窗右上角的关闭按钮来关闭弹窗。 设置为 False 时弹窗仅能通过 popup_close() 关闭,此时 implicit_close 参数将被忽略.

popup() can be used in 2 ways: direct call and context manager.

  • 直接传入内容:

popup('popup title', 'popup text content', size=PopupSize.SMALL)

popup('Popup title', [
    put_html('<h3>Popup Content</h3>'),
    'html: <br/>',
    put_table([['A', 'B'], ['C', 'D']]),
    put_buttons(['close_popup()'], onclick=lambda _: close_popup())
])
  • 作为上下文管理器使用:

with popup('Popup title') as s:
    put_html('<h3>Popup Content</h3>')
    put_text('html: <br/>')
    put_buttons([('clear()', s)], onclick=clear)

put_text('Also work!', scope=s)

上下文管理器会开启一个新的输出scope并返回scope名。在上下文管理器中的输出内容默认会输出到popup窗口中。在上下文管理器退出后,popup窗口并不会随之关闭,你可以继续使用输出函数的 scope 参数来输出内容到popup窗口内。

pywebio.output.close_popup()[源代码]

关闭正在显示的弹窗

See also: popup()

布局与样式

pywebio.output.put_row(content: List[Output | None] = [], size: str = None, scope: str = None, position: int = -1) Output[源代码]

使用行布局输出内容. 内容在水平方向从左往右排列成一行

参数:
  • content (list) – 子元素列表, 列表项为 put_xxx() 调用或者 None , None 表示空白行间距

  • size (str) –

    用于指示子元素的宽度, 为空格分割的宽度值列表.
    宽度值需要和 content 中子元素一一对应( None 子元素也要对应宽度值).
    size 默认给 None 元素分配10像素宽度,并为剩余元素平均分配宽度.

    宽度值可用格式:

    • 像素值: 例如: 100px

    • 百分比: 表示占可用宽度的百分比. 例如: 33.33%

    • fr 关键字: 表示比例关系, 2fr 表示的宽度为 1fr 的两倍

    • auto 关键字: 表示由浏览器自己决定长度

    • minmax(min, max) : 产生一个长度范围,表示长度就在这个范围之中。它接受两个参数,分别为最小值和最大值。 例如: minmax(100px, 1fr) 表示长度不小于100px,不大于1fr

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

Example:

# Two code blocks of equal width, separated by 10 pixels
put_row([put_code('A'), None, put_code('B')])

# The width ratio of the left and right code blocks is 2:3, which is equivalent to size='2fr 10px 3fr'
put_row([put_code('A'), None, put_code('B')], size='40% 10px 60%')
pywebio.output.put_column(content: List[Output | None] = [], size: str = None, scope: str = None, position: int = -1) Output[源代码]

使用列布局输出内容. 内容在竖直方向从上往下排列成一列

参数:
  • content (list) – 子元素列表, 列表项为 put_xxx() 调用或者 None , None 表示空白行间距

  • size (str) – 用于指示子元素的高度, 为空格分割的高度值列表. 可用格式参考 put_row() 函数的 size 参数注释.

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

pywebio.output.put_grid(content: List[List[Output | None]], cell_width: str = 'auto', cell_height: str = 'auto', cell_widths: str = None, cell_heights: str = None, direction: str = 'row', scope: str = None, position: int = -1) Output[源代码]

使用网格布局输出内容

参数:
  • content – 输出内容. put_xxx() / None 组成的二维数组, None 表示空白. 数组项可以使用 span() 函数设置元素在网格的跨度.

  • cell_width (str) – 网格元素的宽度.

  • cell_height (str) – 网格元素的高度.

  • cell_widths (str) – 网格每一列的宽度. 宽度值用空格分隔. 不可以和 cell_width 参数同时使用.

  • cell_heights (str) – 网格每一行的高度. 高度值用空格分隔. 不可以和 cell_height 参数同时使用.

  • direction (str) –

    排列方向. 为 'row''column' .

    'row' 时表示,content中的每一个子数组代表网格的一行;
    'column' 时表示,content中的每一个子数组代表网格的一列.

  • position (int scope,) – 与 put_text 函数的同名参数含义一致

cell_width,``cell_height``,``cell_widths``,``cell_heights`` 参数中的宽度/高度值格式参考 put_row() 函数的 size 参数注释.

Example:

put_grid([
    [put_text('A'), put_text('B'), put_text('C')],
    [None, span(put_text('D'), col=2, row=1)],
    [put_text('E'), put_text('F'), put_text('G')],
], cell_width='100px', cell_height='100px')
pywebio.output.style(outputs: Output | List[Output], css_style: str) Output | OutputList[源代码]

自定义输出内容的css样式

自 1.3 版本弃用: 为输出设置样式的新方式参见 User Guide.

参数:
  • outputs (list/put_xxx()) – 输出内容,可以为 put_xxx() 调用或其列表。outputs为列表时将为每个列表项都添加自定义的css样式。

  • css_style (str) – css样式字符串

返回:

添加了css样式的输出内容

Note: 若 outputs 为list,则 outputs 中每一项都会被添加css样式, 其返回值可用于任何接受 put_xxx() 列表的地方。

Example:

style(put_text('Red'), 'color:red')

style([
    put_text('Red'),
    put_markdown('~~del~~')
], 'color:red')

put_table([
    ['A', 'B'],
    ['C', style(put_text('Red'), 'color:red')],
])

put_collapse('title', style([
    put_text('text'),
    put_markdown('~~del~~'),
], 'margin-left:20px'))