pywebio.input — Get input from web browser

This module provides functions to get all kinds of input of user from the browser

There are two ways to use the input functions, one is to call the input function alone to get a single input:

name = input("What's your name")
print("Your name is %s" % name)

The other is to use input_group to get multiple inputs at once:

info = input_group("User info",[
  input('Input your name', name='name'),
  input('Input your age', name='age', type=NUMBER)
])
print(info['name'], info['age'])

When use input_group, you needs to provide the name parameter in each input function to identify the input items in the result.

Note

PyWebIO determines whether the input function is in input_group or is called alone according to whether the name parameter is passed. So when calling an input function alone, do not set the name parameter; when calling the input function in input_group, you must provide the name parameter.

By default, the user can submit empty input value. If the user must provide a non-empty input value, you need to pass required=True to the input function (some input functions do not support the required parameter)

The input functions in this module is blocking, and the input form will be destroyed after successful submission. If you want the form to always be displayed on the page and receive input continuously, you can consider the pin module.

Functions list

Function name

Description

input

Text input

textarea

Multi-line text input

select

Drop-down selection

checkbox

Checkbox

radio

Radio

slider

Slider

actions

Actions selection

file_upload

File uploading

input_group

Input group

input_update

Update input item

Functions doc

pywebio.input.input(label='', type='text', *, validate=None, name=None, value=None, action=None, onchange=None, placeholder=None, required=None, readonly=None, datalist=None, help_text=None, **other_html_attrs)[source]

Text input

Parameters
  • label (str) – Label of input field.

  • type (str) –

    Input type. Currently supported types are:TEXT , NUMBER , FLOAT , PASSWORD , URL , DATE , TIME

    Note that DATE and TIME type are not supported on some browsers, for details see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Browser_compatibility

  • validate (callable) –

    Input value validation function. If provided, the validation function will be called when user completes the input field or submits the form.

    validate receives the input value as a parameter. When the input value is valid, it returns None. When the input value is invalid, it returns an error message string. For example:

    def check_age(age):
        if age>30:
            return 'Too old'
        elif age<10:
            return 'Too young'
    input('Input your age', type=NUMBER, validate=check_age)
    

  • name (str) – A string specifying a name for the input. Used with input_group() to identify different input items in the results of the input group. If call the input function alone, this parameter can not be set!

  • value (str) – The initial value of the input

  • action (tuple(label:str, callback:callable)) –

    Put a button on the right side of the input field, and user can click the button to set the value for the input.

    label is the label of the button, and callback is the callback function to set the input value when clicked.

    The callback is invoked with one argument, the set_value. set_value is a callable object, which is invoked with one or two arguments. You can use set_value to set the value for the input.

    set_value can be invoked with one argument: set_value(value:str). The value parameter is the value to be set for the input.

    set_value can be invoked with two arguments: set_value(value:any, label:str). Each arguments are described as follows:

    • value : The real value of the input, can be any object. it will not be passed to the user browser.

    • label : The text displayed to the user

    When calling set_value with two arguments, the input item in web page will become read-only.

    The usage scenario of set_value(value:any, label:str) is: You need to dynamically generate the value of the input in the callback, and hope that the result displayed to the user is different from the actual submitted data (for example, result displayed to the user can be some user-friendly texts, and the value of the input can be objects that are easier to process)

    Usage example:

    import time
    def set_now_ts(set_value):
        set_value(int(time.time()))
    
    ts = input('Timestamp', type=NUMBER, action=('Now', set_now_ts))
    from datetime import date,timedelta
    def select_date(set_value):
        with popup('Select Date'):
            put_buttons(['Today'], onclick=[lambda: set_value(date.today(), 'Today')])
            put_buttons(['Yesterday'], onclick=[lambda: set_value(date.today() - timedelta(days=1), 'Yesterday')])
    
    d = input('Date', action=('Select', select_date), readonly=True)
    put_text(type(d), d)
    

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

  • onchange (callable) –

    A callback function which will be called when the value of this input field changed.

    The onchange callback is invoked with one argument, the current value of input field. A typical usage scenario of onchange is to update other input item by using input_update()

  • placeholder (str) – A hint to the user of what can be entered in the input. It will appear in the input field when it has no value set.

  • required (bool) – Whether a value is required for the input to be submittable, default is False

  • readonly (bool) – Whether the value is readonly(not editable)

  • datalist (list) – A list of predefined values to suggest to the user for this input. Can only be used when type=TEXT

  • help_text (str) – Help text for the input. The text will be displayed below the input field with small font

  • other_html_attrs – Additional html attributes added to the input element. reference: https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input#%E5%B1%9E%E6%80%A7

Returns

The value that user input.

pywebio.input.textarea(label='', *, rows=6, code=None, maxlength=None, minlength=None, validate=None, name=None, value=None, onchange=None, placeholder=None, required=None, readonly=None, help_text=None, **other_html_attrs)[source]

Text input area (multi-line text input)

Parameters
  • rows (int) – The number of visible text lines for the input area. Scroll bar will be used when content exceeds.

  • maxlength (int) – The maximum number of characters (UTF-16 code units) that the user can enter. If this value isn’t specified, the user can enter an unlimited number of characters.

  • minlength (int) – The minimum number of characters (UTF-16 code units) required that the user should enter.

  • code (dict/bool) –

    Enable a code style editor by providing the Codemirror options:

    res = textarea('Text area', code={
        'mode': "python",
        'theme': 'darcula'
    })
    

    You can simply use code={} or code=True to enable code style editor. You can use Esc or F11 to toggle fullscreen of code style textarea.

    Some commonly used Codemirror options are listed here.

  • label, validate, name, value, onchange, placeholder, required, readonly, help_text, other_html_attrs (-) – Those arguments have the same meaning as for input()

Returns

The string value that user input.

pywebio.input.select(label='', options=None, *, multiple=None, validate=None, name=None, value=None, onchange=None, required=None, help_text=None, **other_html_attrs)[source]

Drop-down selection

By default, only one option can be selected at a time, you can set multiple parameter to enable multiple selection.

Parameters
  • options (list) –

    list of options. The available formats of the list items are:

    • dict:

      {
          "label":(str) option label,
          "value":(object) option value,
          "selected":(bool, optional) whether the option is initially selected,
          "disabled":(bool, optional) whether the option is initially disabled
      }
      
    • tuple or list: (label, value, [selected,] [disabled])

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

    Attention:

    1. The value of option can be any JSON serializable object

    2. If the multiple is not True, the list of options can only have one selected item at most.

  • multiple (bool) – whether multiple options can be selected

  • value (list or str) – The value of the initial selected item. When multiple=True, value must be a list. You can also set the initial selected option by setting the selected field in the options list item.

  • required (bool) – Whether to select at least one item, only available when multiple=True

  • label, validate, name, onchange, help_text, other_html_attrs (-) – Those arguments have the same meaning as for input()

Returns

If multiple=True, return a list of the values in the options selected by the user; otherwise, return the single value selected by the user.

pywebio.input.checkbox(label='', options=None, *, inline=None, validate=None, name=None, value=None, onchange=None, help_text=None, **other_html_attrs)[source]

A group of check box that allowing single values to be selected/deselected.

Parameters
  • options (list) – List of options. The format is the same as the options parameter of the select() function

  • inline (bool) – Whether to display the options on one line. Default is False

  • value (list) – The value list of the initial selected items. You can also set the initial selected option by setting the selected field in the options list item.

  • label, validate, name, onchange, help_text, other_html_attrs (-) – Those arguments have the same meaning as for input()

Returns

A list of the values in the options selected by the user

pywebio.input.radio(label='', options=None, *, inline=None, validate=None, name=None, value=None, onchange=None, required=None, help_text=None, **other_html_attrs)[source]

A group of radio button. Only a single button can be selected.

Parameters
  • options (list) – List of options. The format is the same as the options parameter of the select() function

  • inline (bool) – Whether to display the options on one line. Default is False

  • value (str) – The value of the initial selected items. You can also set the initial selected option by setting the selected field in the options list item.

  • required (bool) – whether to must select one option. (the user can select nothing option by default)

  • label, validate, name, onchange, help_text, other_html_attrs (-) – Those arguments have the same meaning as for input()

Returns

The value of the option selected by the user, if the user does not select any value, return None

pywebio.input.actions(label='', buttons=None, name=None, help_text=None)[source]

Actions selection

It is displayed as a group of buttons on the page. After the user clicks the button of it, it will behave differently depending on the type of the button.

Parameters
  • buttons (list) –

    list of buttons. The available formats of the list items are:

    • dict:

      {
         "label":(str) button label,
         "value":(object) button value,
         "type":(str, optional) button type,
         "disabled":(bool, optional) whether the button is disabled
      }
      

      When type='reset'/'cancel' or disabled=True, value can be omitted

    • tuple or list: (label, value, [type], [disabled])

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

    The value of button can be any JSON serializable object.

    type can be:

    • 'submit' : After clicking the button, the entire form is submitted immediately, and the value of this input item in the final form is the value of the button that was clicked. 'submit' is the default value of type

    • 'cancel' : Cancel form. After clicking the button, the entire form will be submitted immediately, and the form value will return None

    • 'reset' : Reset form. After clicking the button, the entire form will be reset, and the input items will become the initial state. Note: After clicking the type=reset button, the form will not be submitted, and the actions() call will not return

  • label, name, help_text (-) – Those arguments have the same meaning as for input()

Returns

If the user clicks the type=submit button to submit the form, return the value of the button clicked by the user. If the user clicks the type=cancel button or submits the form by other means, None is returned.

When actions() is used as the last input item in input_group() and contains a button with type='submit', the default submit button of the input_group() form will be replace with the current actions()

usage scenes of ``actions()``

  • Perform simple selection operations:

confirm = actions('Confirm to delete file?', ['confirm', 'cancel'],
                      help_text='Unrecoverable after file deletion')
if confirm=='confirm':  
    ...  

Compared with other input items, when using actions(), the user only needs to click once to complete the submission.

  • Replace the default submit button:

info = input_group('Add user', [
    input('username', type=TEXT, name='username', required=True),
    input('password', type=PASSWORD, name='password', required=True),
    actions('actions', [
        {'label': 'Save', 'value': 'save'},
        {'label': 'Save and add next', 'value': 'save_and_continue'},
        {'label': 'Reset', 'type': 'reset'},
        {'label': 'Cancel', 'type': 'cancel'},
    ], name='action', help_text='actions'),
])
put_code('info = ' + json.dumps(info, indent=4))
if info is not None:
    save_user(info['username'], info['password'])  
    if info['action'] == 'save_and_continue':
        add_next()  
pywebio.input.file_upload(label='', accept=None, name=None, placeholder='Choose file', multiple=False, max_size=0, max_total_size=0, required=None, help_text=None, **other_html_attrs)[source]

File uploading

Parameters
  • accept (str or list) –

    Single value or list, indicating acceptable file types. The available formats of file types are:

  • placeholder (str) – A hint to the user of what to be uploaded. It will appear in the input field when there is no file selected.

  • multiple (bool) – Whether to allow upload multiple files. Default is False.

  • max_size (int/str) –

    The maximum size of a single file, exceeding the limit will prohibit uploading.

    The default is 0, which means there is no limit to the size.

    max_size can be a integer indicating the number of bytes, or a case-insensitive string ending with K / M / G (representing kilobytes, megabytes, and gigabytes, respectively). E.g: max_size=500, max_size='40K', max_size='3M'

  • max_total_size (int/str) – The maximum size of all files. Only available when multiple=True. The default is 0, which means there is no limit to the size. The format is the same as the max_size parameter

  • required (bool) – Indicates whether the user must specify a file for the input. Default is False.

  • label, name, help_text, other_html_attrs (-) – Those arguments have the same meaning as for input()

Returns

When multiple=False, a dict is returned:

{
    'filename': file name,
    'content':content of the file (in bytes),
    'mime_type': MIME type of the file,
    'last_modified': Last modified time (timestamp) of the file
}

If there is no file uploaded, return None.

When multiple=True, a list is returned. The format of the list item is the same as the return value when multiple=False above. If the user does not upload a file, an empty list is returned.

Note

If uploading large files, please pay attention to the file upload size limit setting of the web framework. When using start_server() or path_deploy() to start the PyWebIO application, the maximum file size to be uploaded allowed by the web framework can be set through the max_payload_size parameter.

# Upload a file and save to server                      
f = input.file_upload("Upload a file")                  
open('asset/'+f['filename'], 'wb').write(f['content'])  

imgs = file_upload("Select some pictures:", accept="image/*", multiple=True)
for img in imgs:
    put_image(img['content'])
pywebio.input.slider(label='', *, name=None, value=0, min_value=0, max_value=100, step=1, validate=None, onchange=None, required=None, help_text=None, **other_html_attrs)[source]

Range input.

Parameters
  • value (int/float) – The initial value of the slider.

  • min_value (int/float) – The minimum permitted value.

  • max_value (int/float) – The maximum permitted value.

  • step (int) – The stepping interval. Only available when value, min_value and max_value are all integer.

  • label, name, validate, onchange, required, help_text, other_html_attrs (-) – Those arguments have the same meaning as for input()

Return int/float

If one of value, min_value and max_value is float, the return value is a float, otherwise an int is returned.

pywebio.input.input_group(label='', inputs=None, validate=None, cancelable=False)[source]

Input group. Request a set of inputs from the user at once.

Parameters
  • label (str) – Label of input group.

  • inputs (list) – Input items. The item of the list is the call to the single input function, and the name parameter need to be passed in the single input function.

  • validate (callable) –

    validation function for the group. If provided, the validation function will be called when the user submits the form.

    Function signature: callback(data) -> (name, error_msg). validate receives the value of the entire group as a parameter. When the form value is valid, it returns None. When an input item’s value is invalid, it returns the name value of the item and an error message. For example:

def check_form(data):
    if len(data['name']) > 6:
        return ('name', 'Name to long!')
    if data['age'] <= 0:
        return ('age', 'Age cannot be negative!')

data = input_group("Basic info",[
    input('Input your name', name='name'),
    input('Repeat your age', name='age', type=NUMBER)
], validate=check_form)

put_text(data['name'], data['age'])
Parameters

cancelable (bool) –

Whether the form can be cancelled. Default is False. If cancelable=True, a “Cancel” button will be displayed at the bottom of the form.

Note: If the last input item in the group is actions(), cancelable will be ignored.

Returns

If the user cancels the form, return None, otherwise a dict is returned, whose key is the name of the input item, and whose value is the value of the input item.

pywebio.input.input_update(name=None, **spec)[source]

Update attributes of input field. This function can only be called in onchange callback of input functions.

Parameters
  • name (str) – The name of the target input item. Optional, default is the name of input field which triggers onchange

  • spec – The input parameters need to be updated. Note that those parameters can not be updated: type, name, validate, action, code, onchange, multiple

An example of implementing dependent input items in an input group:

country2city = {
    'China': ['Beijing', 'Shanghai', 'Hong Kong'],
    'USA': ['New York', 'Los Angeles', 'San Francisco'],
}
countries = list(country2city.keys())
location = input_group("Select a location", [
    select('Country', options=countries, name='country',
           onchange=lambda c: input_update('city', options=country2city[c])),
    select('City', options=country2city[countries[0]], name='city'),
])