pywebio_battery
— PyWebIO battery¶
Utilities that help write PyWebIO apps quickly and easily.
Note
pywebio_battery
is an extension package of PyWebIO, you must install it before using it.
To install this package, run pip3 install -U pywebio-battery
Functions index¶
Interaction related¶
Function name |
Description |
Local file picker |
|
Confirmation modal |
|
Show a form in popup window |
|
redirecting stdout to pywebio |
|
Run command in shell |
|
Logbox widget |
|
Output video |
|
Output audio |
Web application related¶
Function name |
Description |
Get URL parameter |
|
User browser storage |
|
Web Cookie |
|
Authentication |
-
pywebio_battery.
file_picker
(path: str, multiple: bool = False, accept: Union[str, List[str]] = '', cancelable: bool = False, title: str = 'File Picker', show_hidden_files: bool = False) → Optional[Union[str, List[str]]][source]¶ A file picker widget that allows you to select files from the local file system where PyWebIO is running.
- Parameters
path (str) – The root path of the file picker.
~
can be used to represent the user’s home directory.multiple (bool) – Whether to allow multiple files to be selected.
accept (str) – Acceptable file type, case-insensitive. Can be a string or a list of strings. e.g.
accept='pdf'
,accept=['jpg', 'png']
. Default is to accept any file.cancelable (bool) – Whether to allow the user to cancel the file picker. By default, the user can only close the file picker by selecting the file.
title (str) – The title of the file picker popup.
show_hidden_files – Whether to show hidden files/folders.
- Returns
The selected file path or a list of file paths.
None
if the user cancels the file picker.
-
pywebio_battery.
confirm
(title: str, content: Optional[Union[str, pywebio.io_ctrl.Output, Sequence[Union[str, pywebio.io_ctrl.Output]]]] = None, *, timeout: Optional[int] = None) → Optional[bool][source]¶ Show a confirmation modal.
- Parameters
title (str) – Model title.
content (list/put_xxx()/str) – The content of the confirmation modal. Can be a string, the put_xxx() calls , or a list of them.
timeout (None/float) – Seconds for operation time out.
- Returns
Return
True
when the “CONFIRM” button is clicked, returnFalse
when the “CANCEL” button is clicked, returnNone
when a timeout is given and the operation times out.
choice = confirm("Delete File", "Are you sure to delete this file?") put_text("Your choice", choice)
-
pywebio_battery.
popup_input
(pins: Union[Sequence[pywebio.io_ctrl.Output], pywebio.io_ctrl.Output], title='Please fill out the form below', validate: Optional[Callable[[Dict], Optional[Tuple[str, str]]]] = None, popup_size: str = 'normal', cancelable: bool = False) → Optional[dict][source]¶ Show a form in popup window.
- Parameters
pins (list) – pin widget list. It can also contain ordinary output widgets.
title (str) – model title.
validate (callable) – validation function for the form. Same as
validate
parameter ininput_group()
popup_size (str) – popup window size. See
size
parameter ofpopup()
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.
- Returns
return the form value as dict, return
None
when user cancel the form.
def check_password(form): if len(form['password']) < 6: return 'password', 'password length must greater than 6' form = popup_input( [ put_input("username", label="Username"), put_input("password", type=PASSWORD, label="Password"), put_info("If you forget your password, please contact the administrator."), ], title="Login", validate=check_password ) put_text("Login info:", form)
-
pywebio_battery.
redirect_stdout
(output_func=functools.partial(<function put_text>, inline=True))[source]¶ Context manager for temporarily redirecting stdout to pywebio.
with redirect_stdout(): print("Hello world.")
-
pywebio_battery.
run_shell
(cmd: str, output_func=functools.partial(<function put_text>, inline=True), encoding='utf8') → int[source]¶ Run command in shell and output the result to pywebio
- Parameters
cmd (str) – command to run
output_func (callable) – output function, default to
put_text()
. the function should accept one argument, the output text of command.encoding (str) – command output encoding
- Returns
shell command return code
Changed in version 0.4: add
encoding
parameter and return code
-
pywebio_battery.
put_logbox
(name: str, height=400, keep_bottom=True) → pywebio.io_ctrl.Output[source]¶ Output a logbox widget
import time put_logbox("log") while True: logbox_append("log", f"{time.time()}\n") time.sleep(0.2)
- Parameters
name (str) – the name of the widget, must unique in session-wide.
height (int) – the height of the widget in pixel
keep_bottom (bool) – Whether to scroll to bottom when new content is appended (via
logbox_append()
).
Changed in version 0.3: add
keep_bottom
parameter
-
pywebio_battery.
put_video
(src: Union[str, bytes], autoplay: bool = False, loop: bool = False, height: Optional[int] = None, width: Optional[int] = None, muted: bool = False, poster: Optional[str] = None, scope: Optional[str] = None, position: int = - 1) → pywebio.io_ctrl.Output[source]¶ Output video
- Parameters
src (str/bytes) – Source of video. It can be a string specifying video URL, a bytes-like object specifying the binary content of the video.
autoplay (bool) – Whether to autoplay the video. In some browsers (e.g. Chrome 70.0) autoplay doesn’t work if not enable
muted
.loop (bool) – If True, the browser will automatically seek back to the start upon reaching the end of the video.
width (int) – The width of the video’s display area, in CSS pixels. If not specified, the intrinsic width of the video is used.
height (int) – The height of the video’s display area, in CSS pixels. If not specified, the intrinsic height of the video is used.
muted (bool) – If set, the audio will be initially silenced.
poster (str) – A URL for an image to be shown while the video is downloading. If this attribute isn’t specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
scope, position (int) – Those arguments have the same meaning as for
put_text()
Example:
url = "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4" put_video(url)
New in version 0.4.
-
pywebio_battery.
put_audio
(src: Union[str, bytes], autoplay: bool = False, loop: bool = False, muted: bool = False, scope: Optional[str] = None, position: int = - 1) → pywebio.io_ctrl.Output[source]¶ Output audio
- Parameters
src (str/bytes) – Source of audio. It can be a string specifying video URL, a bytes-like object specifying the binary content of the audio.
autoplay (bool) – Whether to autoplay the audio.
loop (bool) – If True, the browser will automatically seek back to the start upon reaching the end of the audio.
muted (bool) – If set, the audio will be initially silenced.
scope – The scope of the video. It can be
"session"
or"page"
. If not specified, the video will be automatically removed when the session is closed.scope, position (int) – Those arguments have the same meaning as for
put_text()
Example:
url = "https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3" put_audio(url)
New in version 0.4.
-
pywebio_battery.
wait_scroll_to_bottom
(threshold: float = 10, timeout: Optional[float] = None) → bool[source]¶ Wait until the page is scrolled to bottom.
This function is useful to achieve infinite scrolling.
- param float threshold
If the distance (in pixels) of the browser’s viewport from the bottom of the page is less than the threshold, it is considered to reach the bottom
- param float timeout
Timeout in seconds. The maximum time to wait for the page to scroll to bottom. Default is None, which means no timeout.
- return
Return
True
if the page is scrolled to bottom, returnFalse
only when timeout.
Example:
put_text('This is long text. Scroll to bottom to continue.
- ‘ * 100)
- while True:
wait_scroll_to_bottom() put_text(“New generated content
“*20)
New in version 0.5.
-
pywebio_battery.
get_all_query
()[source]¶ Get URL parameter (also known as “query strings” or “URL query parameters”) as a dict
-
pywebio_battery.
set_localstorage
(key: str, value: str)[source]¶ Save data to user’s web browser
The data is specific to the origin (protocol+domain+port) of the app. Different origins use different web browser local storage.
- Parameters
key – the key you want to create/update.
value – the value you want to give the key you are creating/updating.
You can read the value by using
get_localstorage(key)
-
pywebio_battery.
get_localstorage
(key: str) → str[source]¶ Get the key’s value in user’s web browser local storage
-
pywebio_battery.
basic_auth
(verify_func: Callable[[str, str], bool], secret: Union[str, bytes], expire_days=7, token_name='pywebio_auth_token') → str[source]¶ Persistence authentication with username and password.
You need to provide a function to verify the current user based on username and password. The
basic_auth()
function will save the authentication state in the user’s web browser, so that the authed user does not need to log in again.- Parameters
verify_func (callable) – User authentication function. It should receive two arguments: username and password. If the authentication is successful, it should return
True
, otherwise returnFalse
.secret (str) – HMAC secret for the signature. It should be a long, random str.
expire_days (int) – how many days the auth state can keep valid. After this time, authed users need to log in again.
token_name (str) – the name of the token to store the auth state in user browser.
- Return str
username of the current authed user
Example:
user_name = basic_auth(lambda username, password: username == 'admin' and password == '123', secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__") put_text("Hello, %s. You can refresh this page and see what happen" % user_name)
New in version 0.4.
-
pywebio_battery.
custom_auth
(login_func: Callable[], str], secret=typing.Union[str, bytes], expire_days=7, token_name='pywebio_auth_token') → str[source]¶ Persistence authentication with custom logic.
You need to provide a function to determine the current user and return the username. The
custom_auth()
function will save the authentication state in the user’s web browser, so that the authed user does not need to log in again.- Parameters
login_func (callable) – User login function. It should receive no arguments and return the username of the current user. If fail to verify the current user, it should return
None
.secret (str) – HMAC secret for the signature. It should be a long, random str.
expire_days (int) – how many days the auth state can keep valid. After this time,authed users need to log in again.
token_name (str) – the name of the token to store the auth state in user browser.
- Return str
username of the current authed user.
New in version 0.4.