pywebio.output — Make output to web browser

This module provides functions to output all kinds of content to the user’s browser, and supply flexible output control.

Functions list

The following table shows the output-related functions provided by PyWebIO.
The functions marked with * indicate that they accept put_xxx calls as arguments.
The functions marked with indicate that they can use as context manager.

Name

Description

Output Scope

put_scope

Create a new scope

use_scope

Enter a scope

get_scope

Get the current scope name in the runtime scope stack

clear

Clear the content of scope

remove

Remove the scope

scroll_to

Scroll the page to the scope

Content Outputting

put_text

Output plain text

put_markdown

Output Markdown

Output Messages.

put_html

Output html

put_link

Output link

put_progressbar

Output a progress bar

put_loading

Output loading prompt

put_code

Output code block

put_table*

Output table

Output and update data table

Output button and bind click event

put_image

Output image

put_file

Output a link to download a file

put_tabs*

Output tabs

put_collapse*†

Output collapsible content

put_scrollable*†

Output a fixed height content area,
scroll bar is displayed when the content
exceeds the limit

put_widget*

Output your own widget

Other Interactions

toast

Show a notification message

popup*†

Show popup

close_popup

Close the current popup window.

Layout and Style

put_row*†

Use row layout to output content

put_column*†

Use column layout to output content

put_grid*

Output content using grid layout

span

Cross-cell content

style*

Customize the css style of output content

Output Scope

pywebio.output.put_scope(name: str, content: Union[pywebio.io_ctrl.Output, List[pywebio.io_ctrl.Output]] = [], scope: str = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Output a scope

Parameters
  • name (str) –

  • content (list/put_xxx()) – The initial content of the scope, can be put_xxx() or a list of it.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

pywebio.output.use_scope(name=None, clear=False)[source]

Open or enter a scope. Can be used as context manager and decorator.

See User manual - use_scope()

Parameters
  • name (str) – Scope name. If it is None, a globally unique scope name is generated. (When used as context manager, the context manager will return the scope name)

  • clear (bool) – Whether to clear the contents of the scope before entering the scope.

Usage

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

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

Get the scope name of runtime scope stack

Parameters

stack_idx (int) –

The index of the runtime scope stack. Default is -1.

0 means the top level scope(the ROOT Scope), -1 means the current Scope, -2 means the scope used before entering the current scope, …

Returns

Returns the scope name with the index, and returns None when occurs index error

pywebio.output.clear(scope: Optional[str] = None)[source]

Clear the content of the specified scope

Parameters

scope (str) – Target scope name. Default is the current scope.

pywebio.output.remove(scope: Optional[str] = None)[source]

Remove the specified scope

Parameters

scope (str) – Target scope name. Default is the current scope.

pywebio.output.scroll_to(scope: Optional[str] = None, position: str = 'top')[source]

Scroll the page to the specified scope

Parameters
  • scope (str) – Target scope. Default is the current scope.

  • position (str) –

    Where to place the scope in the visible area of the page. Available value:

    • 'top' : Keep the scope at the top of the visible area of the page

    • 'middle' : Keep the scope at the middle of the visible area of the page

    • 'bottom' : Keep the scope at the bottom of the visible area of the page

Content Outputting

Scope related parameters of output function

The output function will output the content to the “current scope” by default, and the “current scope” for the runtime context can be set by use_scope().

In addition, all output functions support a scope parameter to specify the destination scope to output:

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

The results of the above code are as follows:

text1 in scope3
text2 in scope3
text in ROOT scope

A scope can contain multiple output items, the default behavior of output function is to append its content to target scope. The position parameter of output function can be used to specify the insert position in target scope.

Each output item in a scope has an index, the first item’s index is 0, and the next item’s index is incremented by one. You can also use a negative number to index the items in the scope, -1 means the last item, -2 means the item before the last, …

The position parameter of output functions accepts an integer. When position>=0, it means to insert content before the item whose index equal position; when position<0, it means to insert content after the item whose index equal 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: Optional[str] = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Output plain text

Parameters
  • texts – Texts need to output. The type can be any object, and the str() function will be used for non-string objects.

  • sep (str) – The separator between the texts

  • inline (bool) – Use text as an inline element (no line break at the end of the text). Default is False

  • scope (str) –

    The target scope to output. If the scope does not exist, no operation will be performed.

    Can specify the scope name or use a integer to index the runtime scope stack.

  • position (int) – The position where the content is output in target scope

For more information about scope and position parameter, please refer to User Manual

pywebio.output.put_markdown(mdcontent: str, lstrip: bool = True, options: Optional[Dict[str, Union[str, bool]]] = None, sanitize: bool = True, scope: Optional[str] = None, position: int = - 1, **kwargs)pywebio.io_ctrl.Output[source]

Output Markdown

Parameters
  • mdcontent (str) – Markdown string

  • lstrip (bool) – Whether to remove the leading whitespace in each line of mdcontent. The number of the whitespace to remove will be decided cleverly.

  • options (dict) – Configuration when parsing Markdown. PyWebIO uses marked library to parse Markdown, the parse options see: https://marked.js.org/using_advanced#options (Only supports members of string and boolean type)

  • sanitize (bool) – Whether to use DOMPurify to filter the content to prevent XSS attacks.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

When using Python triple quotes syntax to output multi-line Markdown in a function, you can indent the Markdown text to keep a good code format. PyWebIO will cleverly remove the indent for you when show the Markdown:

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

Changed in version 1.5: Enable lstrip by default. Deprecate strip_indent.

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

Output Messages.

Parameters
  • contents – Message contents. The item is put_xxx() call, and any other type will be converted to put_text(content).

  • closable (bool) – Whether to show a dismiss button on the right of the message.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

New in version 1.2.

pywebio.output.put_html(html: Any, sanitize: bool = False, scope: Optional[str] = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Output HTML content

Parameters
  • html – html string

  • sanitize (bool) –

    Whether to use DOMPurify to filter the content to prevent XSS attacks.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Output hyperlinks to other web page or PyWebIO Application page.

Parameters
  • name (str) – The label of the link

  • url (str) – Target url

  • app (str) – Target PyWebIO Application name. See also: Server mode

  • new_window (bool) – Whether to open the link in a new window

  • scope, position (int) – Those arguments have the same meaning as for put_text()

The url and app parameters must specify one but not both

pywebio.output.put_progressbar(name: str, init: float = 0, label: Optional[str] = None, auto_close: bool = False, scope: Optional[str] = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Output a progress bar

Parameters
  • name (str) – The name of the progress bar, which is the unique identifier of the progress bar

  • init (float) – The initial progress value of the progress bar. The value is between 0 and 1

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

  • auto_close (bool) – Whether to remove the progress bar after the progress is completed

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Example:

import time

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

See also

use set_progressbar() to set the progress of progress bar

pywebio.output.set_progressbar(name: str, value: float, label: Optional[str] = None)[source]

Set the progress of progress bar

Parameters
  • name (str) – The name of the progress bar

  • value (float) – The progress value of the progress bar. The value is between 0 and 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: Optional[str] = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Output loading prompt

Parameters
  • shape (str) – The shape of loading prompt. The available values are: 'border' (default)、 'grow'

  • color (str) – The color of loading prompt. The available values are: 'primary''secondary''success''danger''warning''info''light''dark' (default)

  • scope, position (int) – Those arguments have the same meaning as for put_text()

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

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')

Changed in version 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: Optional[int] = None, scope: Optional[str] = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Output code block

Parameters
  • content (str) – code string

  • language (str) – language of code

  • rows (int) – The max lines of code can be displayed, no limit by default. The scroll bar will be displayed when the content exceeds.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

pywebio.output.put_table(tdata: List[Union[List, Dict]], header: List[Union[str, Tuple[Any, str]]] = None, scope: str = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Output table

Parameters
  • tdata (list) – Table data, which can be a two-dimensional list or a list of dict. The table cell can be a string or put_xxx() call. The cell can use the span() to set the cell span.

  • header (list) –

    Table header. When the item of tdata is of type list, if the header parameter is omitted, the first item of tdata will be used as the header. The header item can also use the span() function to set the cell 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>).

  • scope, position (int) – Those arguments have the same meaning as for 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")]

New in version 0.3: The cell of table support put_xxx() calls.

pywebio.output.span(content: Union[str, pywebio.io_ctrl.Output], row: int = 1, col: int = 1)[source]

Create cross-cell content in put_table() and put_grid()

Parameters
  • content – cell content. It can be a string or put_xxx() call.

  • row (int) – Vertical span, that is, the number of spanning rows

  • col (int) – Horizontal span, that is, the number of spanning columns

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[Union[Dict[str, Any], Tuple[str, Any], List, str]], onclick: Union[Callable[[Any], None], Sequence[Callable[], None]]], small: Optional[bool] = None, link_style: bool = False, outline: bool = False, group: bool = False, scope: Optional[str] = None, position: int = - 1, **callback_options)pywebio.io_ctrl.Output[source]

Output a group of buttons and bind click event

Parameters
  • buttons (list) –

    Button list. The available formats of list items are:

    • dict:

      {
          "label":(str)button label,
          "value":(str)button value,
          "color":(str, optional)button color,
          "disabled":(bool, optional) whether the button is disabled
      }
      
    • tuple or list: (label, value)

    • single value: label and value of option use the same value

    The value of button can be any type. The color of button can be one of: primary, secondary, success, danger, warning, info, light, dark.

    Example:

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

  • onclick (callable / list) –

    Callback which will be called when button is clicked. onclick can be a callable object or a list of it.

    If onclick is callable object, its signature is onclick(btn_value). btn_value is value of the button that is clicked.

    If onclick is a list, the item receives no parameter. In this case, each item in the list corresponds to the buttons one-to-one.

    Tip: You can use functools.partial to save more context information in onclick.

    Note: When in Coroutine-based session, the callback can be a coroutine function.

  • small (bool) – Whether to use small size button. Default is False.

  • link_style (bool) – Whether to use link style button. Default is False

  • outline (bool) – Whether to use outline style button. Default is False

  • group (bool) – Whether to group the buttons together. Default is False

  • scope, position (int) – Those arguments have the same meaning as for put_text()

  • callback_options

    Other options of the onclick callback. There are different options according to the session implementation

    When in Coroutine-based Session:
    • mutex_mode: Default is False. If set to True, new click event will be ignored when the current callback is running. This option is available only when onclick is a coroutine function.

    When in Thread-based Session:
    • serial_mode: Default is False, and every time a callback is triggered, the callback function will be executed immediately in a new thread.

    If set serial_mode to True After enabling serial_mode, the button’s callback will be executed serially in a resident thread in the session, and all other new click event callbacks (including the serial_mode=False callback) will be queued for the current click event to complete. If the callback function runs for a short time, you can turn on serial_mode to improve performance.

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])

Changed in version 1.5: Add disabled button support. The value of button can be any object.

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

Output a single button and bind click event to it.

Parameters
  • label (str) – Button label

  • onclick (callable) – Callback which will be called when button is clicked.

  • color (str) – The color of the button, can be one of: primary, secondary, success, danger, warning, info, light, dark.

  • disabled (bool) – Whether the button is disabled

  • small, link_style, outline, scope, position (-) – Those arguments have the same meaning as for put_buttons()

Example:

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

New in version 1.4.

Changed in version 1.5: add disabled parameter

pywebio.output.put_image(src: Union[str, bytes, PIL.Image.Image], format: Optional[str] = None, title: str = '', width: Optional[str] = None, height: Optional[str] = None, scope: Optional[str] = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Output image

Parameters
  • src – Source of image. It can be a string specifying image URL, a bytes-like object specifying the binary content of an image or an instance of PIL.Image.Image

  • title (str) – Image description.

  • width (str) – The width of image. It can be CSS pixels (like '30px') or percentage (like '10%').

  • height (str) – The height of image. It can be CSS pixels (like '30px') or percentage (like '10%'). If only one value of width and height is specified, the browser will scale image according to its original size.

  • format (str) – Image format, optinoal. e.g.: png, jpeg, gif, etc. Only available when src is non-URL

  • scope, position (int) – Those arguments have the same meaning as for 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: Optional[str] = None, scope: Optional[str] = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Output a link to download a file

To show a link with the file name on the browser. When click the link, the browser automatically downloads the file.

Parameters
  • name (str) – File name downloaded as

  • content – File content. It is a bytes-like object

  • label (str) – The label of the download link, which is the same as the file name by default.

  • scope, position (int) – Those arguments have the same meaning as for 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)pywebio.io_ctrl.Output[source]

Output tabs.

Parameters
  • tabs (list) – Tab list, each item is a dict: {"title": "Title", "content": ...} . The content can be a string, the put_xxx() calls , or a list of them.

  • scope, position (int) – Those arguments have the same meaning as for 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')
    ]},
])

New in version 1.3.

pywebio.output.put_collapse(title: str, content: Union[str, pywebio.io_ctrl.Output, List[Union[str, pywebio.io_ctrl.Output]]] = [], open: bool = False, scope: str = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Output collapsible content

Parameters
  • title (str) – Title of content

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

  • open (bool) – Whether to expand the content. Default is False.

  • scope, position (int) – Those arguments have the same meaning as for 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: Union[str, pywebio.io_ctrl.Output, List[Union[str, pywebio.io_ctrl.Output]]] = [], height: Union[int, Tuple[int, int]] = 400, keep_bottom: bool = False, border: bool = True, scope: str = None, position: int = - 1, **kwargs)pywebio.io_ctrl.Output[source]

Output a fixed height content area. scroll bar is displayed when the content exceeds the limit

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

  • height (int/tuple) – The height of the area (in pixels). height parameter also accepts (min_height, max_height) to indicate the range of height, for example, (100, 200) means that the area has a minimum height of 100 pixels and a maximum of 200 pixels. Set None if you don’t want to limit the height

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

  • border (bool) – Whether to show border

  • scope, position (int) – Those arguments have the same meaning as for 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)

Changed in version 1.1: add height parameter,remove max_height parameter; add keep_bottom parameter

Changed in version 1.5: remove horizon_scroll parameter

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

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.

Parameters
  • 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)[source]

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: Optional[Union[str, int]] = None, field: Optional[Union[str, List[str], Tuple[str]]] = None)[source]

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)[source]

Insert rows to datatable.

Parameters
  • 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)[source]

Remove rows from datatable.

Parameters
  • 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)pywebio.io_ctrl.Output[source]

Output your own widget

Parameters
  • template – html template, using mustache.js syntax

  • data (dict) –

    Data used to render the template.

    The data can include the put_xxx() calls, and the JS function pywebio_output_parse can be used to parse the content of put_xxx(). For string input, pywebio_output_parse will parse into text.

    ⚠️:When using the pywebio_output_parse function, you need to turn off the html escaping of mustache: {{& pywebio_output_parse}}, see the example below.

  • scope, position (int) – Those arguments have the same meaning as for 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'],
        ])
    ]
})

Other Interactions

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

Show a notification message.

Parameters
  • content (str) – Notification content.

  • duration (float) – The duration of the notification display, in seconds. 0 means not to close automatically (at this time, a close button will be displayed next to the message, and the user can close the message manually)

  • position (str) – Where to display the notification message. Available values are 'left', 'center' and 'right'.

  • color (str) – Background color of the notification. Available values are 'info', 'error', 'warn', 'success' or hexadecimal color value starting with '#'

  • onclick (callable) –

    The callback function when the notification message is clicked. The callback function receives no parameters.

    Note: When in Coroutine-based session, the callback can be a coroutine function.

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: Union[str, pywebio.io_ctrl.Output, List[Union[str, pywebio.io_ctrl.Output]]] = None, size: str = 'normal', implicit_close: bool = True, closable: bool = True)[source]

Show a popup.

⚠️: In PyWebIO, you can’t show multiple popup windows at the same time. Before displaying a new pop-up window, the existing popup on the page will be automatically closed. You can use close_popup() to close the popup manually.

Parameters
  • title (str) – The title of the popup.

  • 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) – The size of popup window. Available values are: 'large', 'normal' and 'small'.

  • implicit_close (bool) – If enabled, the popup can be closed implicitly by clicking the content outside the popup window or pressing the Esc key. Default is False.

  • closable (bool) – Whether the user can close the popup window. By default, the user can close the popup by clicking the close button in the upper right of the popup window. When set to False, the popup window can only be closed by popup_close(), at this time the implicit_close parameter will be ignored.

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

  • direct call:

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())
])
  • context manager:

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)

The context manager will open a new output scope and return the scope name. The output in the context manager will be displayed on the popup window by default. After the context manager exits, the popup window will not be closed. You can still use the scope parameter of the output function to output to the popup.

pywebio.output.close_popup()[source]

Close the current popup window.

See also: popup()

Layout and Style

pywebio.output.put_row(content: List[Optional[pywebio.io_ctrl.Output]] = [], size: str = None, scope: str = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Use row layout to output content. The content is arranged horizontally

Parameters
  • content (list) – Content list, the item is put_xxx() call or None. None represents the space between the output

  • size (str) –

    Used to indicate the width of the items, is a list of width values separated by space.
    Each width value corresponds to the items one-to-one. (None item should also correspond to a width value).
    By default, size assigns a width of 10 pixels to the None item, and distributes the width equally to the remaining items.

    Available format of width value are:

    • pixels: like 100px

    • percentage: Indicates the percentage of available width. like 33.33%

    • fr keyword: Represents a scale relationship, 2fr represents twice the width of 1fr

    • auto keyword: Indicates that the length is determined by the browser

    • minmax(min, max) : Generate a length range, indicating that the length is within this range. It accepts two parameters, minimum and maximum. For example: minmax(100px, 1fr) means the length is not less than 100px and not more than 1fr

  • scope, position (int) – Those arguments have the same meaning as for 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[Optional[pywebio.io_ctrl.Output]] = [], size: str = None, scope: str = None, position: int = - 1)pywebio.io_ctrl.Output[source]

Use column layout to output content. The content is arranged vertically

Parameters
  • content (list) – Content list, the item is put_xxx() call or None. None represents the space between the output

  • size (str) – Used to indicate the width of the items, is a list of width values separated by space. The format is the same as the size parameter of the put_row() function.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

pywebio.output.put_grid(content: List[List[Optional[pywebio.io_ctrl.Output]]], 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)pywebio.io_ctrl.Output[source]

Output content using grid layout

Parameters
  • content – Content of grid, which is a two-dimensional list. The item of list is put_xxx() call or None. None represents the space between the output. The item can use the span() to set the cell span.

  • cell_width (str) – The width of grid cell.

  • cell_height (str) – The height of grid cell.

  • cell_widths (str) – The width of each column of the grid. The width values are separated by a space. Can not use cell_widths and cell_width at the same time

  • cell_heights (str) – The height of each row of the grid. The height values are separated by a space. Can not use cell_heights and cell_height at the same time

  • direction (str) –

    Controls how auto-placed items get inserted in the grid. Can be 'row'``(default) or ``'column' .

    'row' : Places items by filling each row
    'column' : Places items by filling each column

  • scope, position (int) – Those arguments have the same meaning as for put_text()

The format of width/height value in cell_width,``cell_height``,``cell_widths``,``cell_heights`` can refer to the size parameter of the put_row() function.

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: Union[pywebio.io_ctrl.Output, List[pywebio.io_ctrl.Output]], css_style: str)Union[pywebio.io_ctrl.Output, pywebio.io_ctrl.OutputList][source]

Customize the css style of output content

Deprecated since version 1.3: See User Guide for new way to set css style for output.

Parameters
  • outputs (list/put_xxx()) – The output content can be a put_xxx() call or a list of it.

  • css_style (str) – css style string

Returns

The output contents with css style added:

Note: If outputs is a list of put_xxx() calls, the style will be set for each item of the list. And the return value can be used in anywhere accept a list of put_xxx() calls.

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'))