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 |
Text input |
|
Multi-line text input |
|
Drop-down selection |
|
Checkbox |
|
Radio |
|
Slider |
|
Actions selection |
|
File uploading |
|
Input group |
|
Update input item |
Functions doc
- pywebio.input.input(label: str = '', type: str = 'text', *, validate: Callable[[Any], str | None] | None = None, name: str | None = None, value: str | int | None = None, action: Tuple[str, Callable[[Callable], None]] | None = None, onchange: Callable[[Any], None] | None = None, placeholder: str | None = None, required: bool | None = None, readonly: bool | None = None, datalist: List[str] | None = None, help_text: str | None = 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
,DATETIME
,COLOR
The value of
DATE
,TIME
,DATETIME
type is a string in the format ofYYYY-MM-DD
,HH:MM:SS
,YYYY-MM-DDTHH:MM
respectively (%Y-%m-%d
,%H:%M:%S
,%Y-%m-%dT%H:%M
in python strptime() format).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 returnsNone
. 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, andcallback
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 useset_value
to set the value for the input.set_value
can be invoked with one argument:set_value(value:str)
. Thevalue
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 user change the value of this input field.
The
onchange
callback is invoked with one argument, the current value of input field. A typical usage scenario ofonchange
is to update other input item by usinginput_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: str = '', *, rows: int = 6, code: bool | Dict | None = None, maxlength: int | None = None, minlength: int | None = None, validate: Callable[[Any], str | None] | None = None, name: str | None = None, value: str | None = None, onchange: Callable[[Any], None] | None = None, placeholder: str | None = None, required: bool | None = None, readonly: bool | None = None, help_text: str | None = 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={}
orcode=True
to enable code style editor. You can useEsc
orF11
to toggle fullscreen of code style textarea.Some commonly used Codemirror options are listed here.
other_html_attrs (- label, validate, name, value, onchange, placeholder, required, readonly, help_text,) – Those arguments have the same meaning as for
input()
- Returns:
The string value that user input.
- pywebio.input.select(label: str = '', options: List[Dict[str, Any] | Tuple | List | str] | None = None, *, multiple: bool | None = None, validate: Callable[[Any], str | None] | None = None, name: str | None = None, value: List | str | None = None, onchange: Callable[[Any], None] | None = None, native: bool = True, required: bool | None = None, help_text: str | None = 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:
The
value
of option can be any JSON serializable objectIf the
multiple
is notTrue
, the list of options can only have oneselected
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 theselected
field in theoptions
list item.required (bool) – Whether to select at least one item, only available when
multiple=True
native (bool) – Using browser’s native select component rather than bootstrap-select. This is the default behavior.
other_html_attrs (- label, validate, name, onchange, help_text,) – Those arguments have the same meaning as for
input()
- Returns:
If
multiple=True
, return a list of the values in theoptions
selected by the user; otherwise, return the single value selected by the user.
- pywebio.input.checkbox(label: str = '', options: List[Dict[str, Any] | Tuple | List | str] | None = None, *, inline: bool | None = None, validate: Callable[[Any], str | None] | None = None, name: str | None = None, value: List | None = None, onchange: Callable[[Any], None] | None = None, help_text: str | None = 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 theselect()
functioninline (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 theoptions
list item.other_html_attrs (- label, validate, name, onchange, help_text,) – 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: str = '', options: List[Dict[str, Any] | Tuple | List | str] | None = None, *, inline: bool | None = None, validate: Callable[[Any], str | None] | None = None, name: str | None = None, value: str | None = None, onchange: Callable[[Any], None] | None = None, required: bool | None = None, help_text: str | None = 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 theselect()
functioninline (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 theoptions
list item.required (bool) – whether to must select one option. (the user can select nothing option by default)
other_html_attrs (- label, validate, name, onchange, help_text,) – 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: str = '', buttons: List[Dict[str, Any] | Tuple | List | str] | None = None, name: str | None = None, help_text: str | None = 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, "color":(str, optional) button color }
When
type='reset'/'cancel'
ordisabled=True
,value
can be omittedtuple 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 thevalue
of the button that was clicked.'submit'
is the default value oftype
'cancel'
: Cancel form. After clicking the button, the entire form will be submitted immediately, and the form value will returnNone
'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 thetype=reset
button, the form will not be submitted, and theactions()
call will not return
The
color
of button can be one of:primary
,secondary
,success
,danger
,warning
,info
,light
,dark
.help_text (- label, name,) – 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 thetype=cancel
button or submits the form by other means,None
is returned.
When
actions()
is used as the last input item ininput_group()
and contains a button withtype='submit'
, the default submit button of theinput_group()
form will be replace with the currentactions()
**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', 'color': 'warning'}, {'label': 'Cancel', 'type': 'cancel', 'color': 'danger'}, ], 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: str = '', accept: List | str | None = None, name: str | None = None, placeholder: str = 'Choose file', multiple: bool = False, max_size: int | str = 0, max_total_size: int | str = 0, required: bool | None = None, help_text: str | None = 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:
A valid case-insensitive filename extension, starting with a period (“.”) character. For example:
.jpg
,.pdf
, or.doc
.A valid MIME type string, with no extensions. For examples:
application/pdf
,audio/*
,video/*
,image/*
. For more information, please visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
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 withK
/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 themax_size
parameterrequired (bool) – Indicates whether the user must specify a file for the input. Default is
False
.other_html_attrs (- label, name, help_text,) – 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 whenmultiple=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()
orpath_deploy()
to start the PyWebIO application, the maximum file size to be uploaded allowed by the web framework can be set through themax_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: str = '', *, name: str | None = None, value: int | float = 0, min_value: int | float = 0, max_value: int | float = 100, step: int = 1, validate: Callable[[Any], str | None] | None = None, onchange: Callable[[Any], None] | None = None, required: bool | None = None, help_text: str | None = 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
andmax_value
are all integer.other_html_attrs (- label, name, validate, onchange, required, help_text,) – Those arguments have the same meaning as for
input()
- Return int/float:
If one of
value
,min_value
andmax_value
is float, the return value is a float, otherwise an int is returned.
- pywebio.input.input_group(label: str = '', inputs: List | None = None, validate: Callable[[Dict], Tuple[str, str] | None] | None = None, cancelable: bool = 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 returnsNone
. When an input item’s value is invalid, it returns thename
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
. Ifcancelable=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 adict
is returned, whose key is thename
of the input item, and whose value is the value of the input item.
- pywebio.input.input_update(name: str | None = 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 triggersonchange
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'), ])