pywebio_battery — PyWebIO battery

Utilities that help write PyWebIO apps quickly and easily.

备注

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

pywebio_battery.file_picker(path: str, multiple: bool = False, accept: str | List[str] = '', cancelable: bool = False, title: str = 'File Picker', show_hidden_files: bool = False) str | List[str] | None[源代码]

A file picker widget that allows you to select files from the local file system where PyWebIO is running.

参数:
  • 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.

返回:

The selected file path or a list of file paths. None if the user cancels the file picker.

files = file_picker('.', multiple=True, accept='py')
put_text(files)
pywebio_battery.confirm(title: str, content: str | Output | Sequence[str | Output] | None = None, *, timeout: int | None = None) bool | None[源代码]

Show a confirmation modal.

参数:
  • 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.

返回:

Return True when the “CONFIRM” button is clicked, return False when the “CANCEL” button is clicked, return None 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: Sequence[Output] | Output, title='Please fill out the form below', validate: Callable[[Dict], Tuple[str, str] | None] | None = None, popup_size: str = 'normal', cancelable: bool = False) dict | None[源代码]

Show a form in popup window.

参数:
  • 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 in input_group()

  • popup_size (str) – popup window size. See size parameter of popup()

  • 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.

返回:

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))[源代码]

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[源代码]

Run command in shell and output the result to pywebio

参数:
  • 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

返回:

shell command return code

在 0.4 版本发生变更: add encoding parameter and return code

cmd = "ls -l"
put_logbox('shell_output')
run_shell(cmd, output_func=lambda msg: logbox_append('shell_output', msg))
pywebio_battery.put_logbox(name: str, height=400, keep_bottom=True) Output[源代码]

Output a logbox widget

import time

put_logbox("log")
while True:
    logbox_append("log", f"{time.time()}\n")
    time.sleep(0.2)
参数:
  • 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()).

在 0.3 版本发生变更: add keep_bottom parameter

pywebio_battery.logbox_append(name: str, text: str)[源代码]

Append text to a logbox widget

pywebio_battery.logbox_clear(name: str)[源代码]

Clear all contents of a logbox widget

pywebio_battery.put_video(src: str | bytes, autoplay: bool = False, loop: bool = False, height: int | None = None, width: int | None = None, muted: bool = False, poster: str | None = None, scope: str | None = None, position: int = -1) Output[源代码]

Output video

参数:
  • 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.

  • position (int scope,) – 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)

Added in version 0.4.

pywebio_battery.put_audio(src: str | bytes, autoplay: bool = False, loop: bool = False, muted: bool = False, scope: str | None = None, position: int = -1) Output[源代码]

Output audio

参数:
  • 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.

    备注

    Web browsers typically don’t allow autoplaying audio without user interaction. If you want to autoplay audio, one way is to call put_audio(autoplay=True) in a callback function of a button. See also: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

  • 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.

  • position (int scope,) – 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)

Added in version 0.4.

pywebio_battery.wait_scroll_to_bottom(threshold: float = 10, timeout: float | None = None) bool[源代码]

Wait until the page is scrolled to bottom.

This function is useful to achieve infinite scrolling.

参数:
  • threshold (float) – 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

  • timeout (float) – Timeout in seconds. The maximum time to wait for the page to scroll to bottom. Default is None, which means no timeout.

返回:

Return True if the page is scrolled to bottom, return False only when timeout.

Example:

put_text('This is long text. Scroll to bottom to continue.\n' * 100)
while True:
    wait_scroll_to_bottom()
    put_text("New generated content\n"*20)

Added in version 0.5.

pywebio_battery.get_all_query()[源代码]

Get URL parameter (also known as “query strings” or “URL query parameters”) as a dict

pywebio_battery.get_query(name: str)[源代码]

Get URL parameter value

pywebio_battery.set_localstorage(key: str, value: str)[源代码]

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.

参数:
  • 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[源代码]

Get the key’s value in user’s web browser local storage

Set cookie

Get cookie

pywebio_battery.basic_auth(verify_func: Callable[[str, str], bool], secret: str | bytes, expire_days=7, token_name='pywebio_auth_token') str[源代码]

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.

参数:
  • verify_func (callable) – User authentication function. It should receive two arguments: username and password. If the authentication is successful, it should return True, otherwise return False.

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

Added 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[源代码]

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.

参数:
  • 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.

Added in version 0.4.

pywebio_battery.revoke_auth(token_name='pywebio_auth_token')[源代码]

Revoke the auth state of current user

参数:

token_name (str) – the name of the token to store the auth state in user browser.

Added in version 0.4.