pywebio.session — More control to session

pywebio.session.download(name, content)[source]

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

Parameters
  • name (str) – File name when downloading

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

Example:

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.

Parameters
  • code (str) – JavaScript code

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

Example:

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

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

Returns

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.

Example:

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: threading.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

Parameters

thread (threading.Thread) – Thread object

pywebio.session.defer_call(func)[source]

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:

@defer_call
def cleanup():
   pass

Attention

PyWebIO interactive functions cannot be called inside the deferred functions.

pywebio.session.local

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):
    put_text(cnt[0])

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_text(cnt)

    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.

local.name = "Wang"
local.age = 22
assert local.foo is None
local[10] = "10"

for key in local:
    print(key)

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

print(local._dict)

New in version 1.1.

pywebio.session.set_env(**env_info)[source]

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

Example:

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

Parameters
  • name (str) – Target PyWebIO task name.

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

See also: Server mode

pywebio.session.info

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

    • browser.family (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’

    • os.family (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’

    • device.family (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 https://github.com/selwin/python-user-agents#usage

Changed in version 1.2: Added the protocol attribute.

Example:

import json
from pywebio.session import info as session_info

put_code(json.dumps({
    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()[source]

Close the coroutine task.

closed()bool[source]

Returns a bool stating whether the coroutine task is closed.

pywebio.session.hold()[source]

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

Attention

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

pywebio.session.run_async(coro_obj)[source]

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

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

Parameters

coro_obj – Coroutine object

Returns

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

pywebio.session.run_asyncio_coroutine(coro_obj)[source]

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.

Parameters

coro_obj – Coroutine object in asyncio

Example:

async def app():
    put_text('hello')
    await run_asyncio_coroutine(asyncio.sleep(1))
    put_text('world')

pywebio.platform.flask.start_server(app)