pywebio.session — More control to session, content)[source]

Send file to user, and the user browser will download the file to the local

  • name (str) – File name when downloading

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


put_button('Click to download', lambda: download('hello-world.txt', b'hello world!'))
pywebio.session.run_js(code_, **args)[source]

Execute JavaScript code in user browser.

The code is run in the browser’s JS global scope.

  • code (str) – JavaScript code

  • args – Local variables passed to js code. Variables need to be JSON-serializable.


run_js('console.log(a + b)', a=1, b=2)
pywebio.session.eval_js(expression_, **args)[source]

Execute JavaScript expression in the user’s browser and get the value of the expression

  • expression (str) – JavaScript expression. The value of the expression need to be JSON-serializable. If the value of the expression is a promise, eval_js() will wait for the promise to resolve and return the value of it. When the promise is rejected, None is returned.

  • args – Local variables passed to js code. Variables need to be JSON-serializable.


The value of the expression.

Note: When using coroutine-based session, you need to use the await eval_js(expression) syntax to call the function.


current_url = eval_js("window.location.href")

function_res = eval_js('''(function(){
    var a = 1;
    a += b;
    return a;
})()''', b=100)

promise_res = eval_js('''new Promise(resolve => {
    setTimeout(() => {
        resolve('Returned inside callback.');
    }, 2000);

Changed in version 1.3: The JS expression support return promise.

pywebio.session.register_thread(thread: Thread)[source]

Register the thread so that PyWebIO interactive functions are available in the thread.

Can only be used in the thread-based session.

See Concurrent in Server mode


thread (threading.Thread) – Thread object


Set the function to be called when the session closes.

Whether it is because the user closes the page or the task finishes to cause session closed, the function set by defer_call(func) will be executed. Can be used for resource cleaning.

You can call defer_call(func) multiple times in the session, and the set functions will be executed sequentially after the session closes.

defer_call() can also be used as decorator:

def cleanup():


PyWebIO interactive functions cannot be called inside the deferred functions.


The session-local object for current session.

local is a dictionary object that can be accessed through attributes, it aim to be used to save some session-local state of your application. Attributes of local are not shared between sessions, each session sees only the attributes it itself placed in there.

Usage Scenes:

When you need to share some session-independent data with multiple functions, it is more convenient to use session-local objects to save state than to use function parameters.

Here is a example of a session independent counter implementation:

from pywebio.session import local
def add():
    local.cnt = (local.cnt or 0) + 1

def show():
    put_text(local.cnt or 0)

def main():
    put_buttons(['Add counter', 'Show counter'], [add, show])

The way to pass state through function parameters is:

from functools import partial
def add(cnt):
    cnt[0] += 1

def show(cnt):

def main():
    cnt = [0]  # Trick: to pass by reference
    put_buttons(['Add counter', 'Show counter'], [partial(add, cnt), partial(show, cnt)])

Of course, you can also use function closures to achieved the same:

def main():
    cnt = 0

    def add():
        nonlocal cnt
        cnt += 1

    def show():

    put_buttons(['Add counter', 'Show counter'], [add, show])
Operations supported by local object:

local is a dictionary object that can be accessed through attributes. When accessing a property that does not exist in the data object, it returns None instead of throwing an exception. The method of dictionary is not supported in local. It supports the in operator to determine whether the key exists. You can use local._dict to get the underlying dictionary data. = "Wang"
local.age = 22
assert is None
local[10] = "10"

for key in local:

assert 'bar' not in local
assert 'name' in local


Added in version 1.1.


configure the environment of current session.

Available configuration are:

  • title (str): Title of current page.

  • output_animation (bool): Whether to enable output animation, enabled by default

  • auto_scroll_bottom (bool): Whether to automatically scroll the page to the bottom after output content, it is closed by default. Note that after enabled, only outputting to ROOT scope can trigger automatic scrolling.

  • http_pull_interval (int): The period of HTTP polling messages (in milliseconds, default 1000ms), only available in sessions based on HTTP connection.

  • input_panel_fixed (bool): Whether to make input panel fixed at bottom, enabled by default

  • input_panel_min_height (int): The minimum height of input panel (in pixel, default 300px), it should be larger than 75px. Available only when input_panel_fixed=True

  • input_panel_init_height (int): The initial height of input panel (in pixel, default 300px), it should be larger than 175px. Available only when input_panel_fixed=True

  • input_auto_focus (bool): Whether to focus on input automatically after showing input panel, default is True

  • output_max_width (str): The max width of the page content area (in pixel or percentage, e.g. '1080px', '80%'. Default is 880px).


set_env(title='Awesome PyWebIO!!', output_animation=False)

Changed in version 1.4: Added the output_max_width parameter

pywebio.session.go_app(name, new_window=True)[source]

Jump to another task of a same PyWebIO application. Only available in PyWebIO Server mode

  • name (str) – Target PyWebIO task name.

  • new_window (bool) – Whether to open in a new window, the default is True

See also: Server mode

The session information data object, whose attributes are:

  • user_agent : The Object of the user browser information, whose attributes are

    • is_mobile (bool): whether user agent is identified as a mobile phone (iPhone, Android phones, Blackberry, Windows Phone devices etc)

    • is_tablet (bool): whether user agent is identified as a tablet device (iPad, Kindle Fire, Nexus 7 etc)

    • is_pc (bool): whether user agent is identified to be running a traditional “desktop” OS (Windows, OS X, Linux)

    • is_touch_capable (bool): whether user agent has touch capabilities

    • (str): Browser family. such as ‘Mobile Safari’

    • browser.version (tuple): Browser version. such as (5, 1)

    • browser.version_string (str): Browser version string. such as ‘5.1’

    • (str): User OS family. such as ‘iOS’

    • os.version (tuple): User OS version. such as (5, 1)

    • os.version_string (str): User OS version string. such as ‘5.1’

    • (str): User agent’s device family. such as ‘iPhone’

    • device.brand (str): Device brand. such as ‘Apple’

    • device.model (str): Device model. such as ‘iPhone’

  • user_language (str): Language used by the user’s operating system. (e.g., 'zh-CN')

  • server_host (str): PyWebIO server host, including domain and port, the port can be omitted when 80.

  • origin (str): Indicate where the user from. Including protocol, host, and port parts. Such as 'http://localhost:8080'. It may be empty, but it is guaranteed to have a value when the user’s page address is not under the server host. (that is, the host, port part are inconsistent with server_host).

  • user_ip (str): User’s ip address.

  • backend (str): The current PyWebIO backend server implementation. The possible values are 'tornado', 'flask', 'django' , 'aiohttp' , 'starlette'.

  • protocol (str): The communication protocol between PyWebIO server and browser. The possible values are 'websocket', 'http'

  • request (object): The request object when creating the current session. Depending on the backend server, the type of request can be:

The user_agent attribute of the session information object is parsed by the user-agents library. See

Changed in version 1.2: Added the protocol attribute.


import json
from pywebio.session import info as session_info

    k: str(getattr(session_info, k))
    for k in ['user_agent', 'user_language', 'server_host',
              'origin', 'user_ip', 'backend', 'protocol', 'request']
}, indent=4), 'json')
class pywebio.session.coroutinebased.TaskHandler(close, closed)[source]

The handler of coroutine task

See also: run_async()


Close the coroutine task.

closed() bool[source]

Returns a bool stating whether the coroutine task is closed.


Keep the session alive until the browser page is closed by user.


Since PyWebIO v1.4, in server mode, it’s no need to call this function manually, PyWebIO will automatically hold the session for you when needed. The only case to use it is to prevent the application from exiting in script mode.

In case you use the previous version of PyWebIO (we strongly recommend that you upgrade to the latest version), here is the old document for hold():

After the PyWebIO session closed, the functions that need communicate with the PyWebIO server (such as the event callback of put_buttons() and download link of put_file()) will not work. You can call the hold() function at the end of the task function to hold the session, so that the event callback and download link will always be available before the browser page is closed by user.


Run the coroutine object asynchronously. PyWebIO interactive functions are also available in the coroutine.

run_async() can only be used in coroutine-based session.


coro_obj – Coroutine object


TaskHandle instance, which can be used to query the running status of the coroutine or close the coroutine.

See also: Concurrency in coroutine-based sessions


If the thread running sessions are not the same as the thread running the asyncio event loop, you need to wrap run_asyncio_coroutine() to run the coroutine in asyncio.

Can only be used in coroutine-based session.


coro_obj – Coroutine object in asyncio


async def app():
    await run_asyncio_coroutine(asyncio.sleep(1))