pywebio.platform — Deploy applications

The platform module provides support for deploying PyWebIO applications in different ways.

Directory Deploy

You can use path_deploy() or path_deploy_http() to deploy the PyWebIO applications from a directory. The python file under this directory need contain the main function to be seen as the PyWebIO application. You can access the application by using the file path as the URL.

Note that users can’t view and access files or folders whose name begin with the underscore in this directory.

For example, given the following folder structure:

.
├── A
│   └── a.py
├── B
│   └── b.py
└── c.py

All three python files contain main PyWebIO application function.

If you use this directory in path_deploy(), you can access the PyWebIO application in b.py by using URL http://<host>:<port>/A/b. And if the files have been modified after run path_deploy(), you can use reload URL parameter to reload application in the file: http://<host>:<port>/A/b?reload

You can also use the command pywebio-path-deploy to start a server just like using path_deploy(). For more information, refer pywebio-path-deploy --help

pywebio.platform.path_deploy(base, port=0, host='', index=True, static_dir=None, reconnect_timeout=0, cdn=True, debug=True, allowed_origins=None, check_origin=None, max_payload_size='200M', **tornado_app_settings)[source]

Deploy the PyWebIO applications from a directory.

The server communicates with the browser using WebSocket protocol.

Parameters
  • base (str) – Base directory to load PyWebIO application.

  • port (int) – The port the server listens on.

  • host (str) – The host the server listens on.

  • index (bool/callable) –

    Whether to provide a default index page when request a directory, default is True. index also accepts a function to custom index page, which receives the requested directory path as parameter and return HTML content in string.

    You can override the index page by add a index.py PyWebIO app file to the directory.

  • static_dir (str) – Directory to store the application static files. The files in this directory can be accessed via http://<host>:<port>/static/files. For example, if there is a A/B.jpg file in static_dir path, it can be accessed via http://<host>:<port>/static/A/B.jpg.

  • reconnect_timeout (int) – The client can reconnect to server within reconnect_timeout seconds after an unexpected disconnection. If set to 0 (default), once the client disconnects, the server session will be closed.

The rest arguments of path_deploy() have the same meaning as for pywebio.platform.tornado.start_server()

pywebio.platform.path_deploy_http(base, port=0, host='', index=True, static_dir=None, cdn=True, debug=True, allowed_origins=None, check_origin=None, session_expire_seconds=None, session_cleanup_interval=None, max_payload_size='200M', **tornado_app_settings)[source]

Deploy the PyWebIO applications from a directory.

The server communicates with the browser using HTTP protocol.

The base, port, host, index, static_dir arguments of path_deploy_http() have the same meaning as for pywebio.platform.path_deploy()

The rest arguments of path_deploy_http() have the same meaning as for pywebio.platform.tornado_http.start_server()

Application Deploy

The start_server() functions can start a Python Web server and serve given PyWebIO applications on it.

The webio_handler() and webio_view() functions can be used to integrate PyWebIO applications into existing Python Web project.

The wsgi_app() and asgi_app() is used to get the WSGI or ASGI app for running PyWebIO applications. This is helpful when you don’t want to start server with the Web framework built-in’s. For example, you want to use other WSGI server, or you are deploying app in a cloud environment. Note that only Flask, Django and FastApi backend support it.

Changed in version 1.1: Added the cdn parameter in start_server(), webio_handler() and webio_view().

Changed in version 1.2: Added the static_dir parameter in start_server().

Changed in version 1.3: Added the wsgi_app() and asgi_app().

Tornado support

There are two protocols (WebSocket and HTTP) can be used to communicates with the browser:

WebSocket

pywebio.platform.tornado.start_server(applications, port=0, host='', debug=False, cdn=True, static_dir=None, remote_access=False, reconnect_timeout=0, allowed_origins=None, check_origin=None, auto_open_webbrowser=False, max_payload_size='200M', **tornado_app_settings)[source]

Start a Tornado server to provide the PyWebIO application as a web service.

The Tornado server communicates with the browser by WebSocket protocol.

Tornado is the default backend server for PyWebIO applications, and start_server can be imported directly using from pywebio import start_server.

Parameters
  • applications (list/dict/callable) –

    PyWebIO application. Can be a task function, a list of functions, or a dictionary. Refer to Advanced topic: Multiple applications in start_server() for more information.

    When the task function is a coroutine function, use Coroutine-based session implementation, otherwise, use thread-based session implementation.

  • port (int) – The port the server listens on. When set to 0, the server will automatically select a available port.

  • host (str) – The host the server listens on. host may be either an IP address or hostname. If it’s a hostname, the server will listen on all IP addresses associated with the name. host may be an empty string or None to listen on all available interfaces.

  • debug (bool) – Tornado Server’s debug mode. If enabled, the server will automatically reload for code changes. See tornado doc for more detail.

  • cdn (bool/str) – Whether to load front-end static resources from CDN, the default is True. Can also use a string to directly set the url of PyWebIO static resources.

  • static_dir (str) – The directory to store the application static files. The files in this directory can be accessed via http://<host>:<port>/static/files. For example, if there is a A/B.jpg file in static_dir path, it can be accessed via http://<host>:<port>/static/A/B.jpg.

  • remote_access (bool) – Whether to enable remote access, when enabled, you can get a temporary public network access address for the current application, others can access your application via this address.

  • auto_open_webbrowser (bool) – Whether or not auto open web browser when server is started (if the operating system allows it) .

  • reconnect_timeout (int) – The client can reconnect to server within reconnect_timeout seconds after an unexpected disconnection. If set to 0 (default), once the client disconnects, the server session will be closed.

  • allowed_origins (list) –

    The allowed request source list. (The current server host is always allowed) The source contains the protocol, domain name, and port part. Can use Unix shell-style wildcards:

    • * matches everything

    • ? matches any single character

    • [seq] matches any character in seq

    • [!seq] matches any character not in seq

    Such as: https://*.example.com*://*.example.com

    For detail, see Python Doc

  • check_origin (callable) – The validation function for request source. It receives the source string (which contains protocol, host, and port parts) as parameter and return True/False to indicate that the server accepts/rejects the request. If check_origin is set, the allowed_origins parameter will be ignored.

  • auto_open_webbrowser – Whether or not auto open web browser when server is started (if the operating system allows it) .

  • max_payload_size (int/str) – Max size of a websocket message which Tornado can accept. Messages larger than the max_payload_size (default 200MB) will not be accepted. max_payload_size can be a integer indicating the number of bytes, or a string ending with K / M / G (representing kilobytes, megabytes, and gigabytes, respectively). E.g: 500, '40K', '3M'

  • tornado_app_settings – Additional keyword arguments passed to the constructor of tornado.web.Application. For details, please refer: https://www.tornadoweb.org/en/stable/web.html#tornado.web.Application.settings

pywebio.platform.tornado.webio_handler(applications, cdn=True, reconnect_timeout=0, allowed_origins=None, check_origin=None)[source]

Get the RequestHandler class for running PyWebIO applications in Tornado. The RequestHandler communicates with the browser by WebSocket protocol.

The arguments of webio_handler() have the same meaning as for pywebio.platform.tornado.start_server()

HTTP

pywebio.platform.tornado_http.start_server(applications, port=8080, host='', debug=False, cdn=True, static_dir=None, allowed_origins=None, check_origin=None, auto_open_webbrowser=False, session_expire_seconds=None, session_cleanup_interval=None, max_payload_size='200M', **tornado_app_settings)[source]

Start a Tornado server to provide the PyWebIO application as a web service.

The Tornado server communicates with the browser by HTTP protocol.

Parameters
  • session_expire_seconds (int) – Session expiration time, in seconds(default 60s). If no client message is received within session_expire_seconds, the session will be considered expired.

  • session_cleanup_interval (int) – Session cleanup interval, in seconds(default 120s). The server will periodically clean up expired sessions and release the resources occupied by the sessions.

  • max_payload_size (int/str) – Max size of a request body which Tornado can accept.

The rest arguments of start_server() have the same meaning as for pywebio.platform.tornado.start_server()

New in version 1.2.

pywebio.platform.tornado_http.webio_handler(applications, cdn=True, session_expire_seconds=None, session_cleanup_interval=None, allowed_origins=None, check_origin=None)[source]

Get the RequestHandler class for running PyWebIO applications in Tornado. The RequestHandler communicates with the browser by HTTP protocol.

The arguments of webio_handler() have the same meaning as for pywebio.platform.tornado_http.start_server()

New in version 1.2.

Flask support

When using the Flask as PyWebIO backend server, you need to install Flask by yourself and make sure the version is not less than 0.10. You can install it with the following command:

pip3 install -U flask>=0.10
pywebio.platform.flask.webio_view(applications, cdn=True, session_expire_seconds=None, session_cleanup_interval=None, allowed_origins=None, check_origin=None)[source]

Get the view function for running PyWebIO applications in Flask. The view communicates with the browser by HTTP protocol.

The arguments of webio_view() have the same meaning as for pywebio.platform.flask.start_server()

pywebio.platform.flask.wsgi_app(applications, cdn=True, static_dir=None, allowed_origins=None, check_origin=None, session_expire_seconds=None, session_cleanup_interval=None, max_payload_size='200M')[source]

Get the Flask WSGI app for running PyWebIO applications.

The arguments of wsgi_app() have the same meaning as for pywebio.platform.flask.start_server()

pywebio.platform.flask.start_server(applications, port=8080, host='', cdn=True, static_dir=None, remote_access=False, allowed_origins=None, check_origin=None, session_expire_seconds=None, session_cleanup_interval=None, debug=False, max_payload_size='200M', **flask_options)[source]

Start a Flask server to provide the PyWebIO application as a web service.

Parameters
  • session_expire_seconds (int) – Session expiration time, in seconds(default 600s). If no client message is received within session_expire_seconds, the session will be considered expired.

  • session_cleanup_interval (int) – Session cleanup interval, in seconds(default 300s). The server will periodically clean up expired sessions and release the resources occupied by the sessions.

  • debug (bool) – Flask debug mode. If enabled, the server will automatically reload for code changes.

  • max_payload_size (int/str) – Max size of a request body which Flask can accept.

  • flask_options – Additional keyword arguments passed to the flask.Flask.run. For details, please refer: https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.run

The arguments of start_server() have the same meaning as for pywebio.platform.tornado.start_server()

Django support

When using the Django as PyWebIO backend server, you need to install Django by yourself and make sure the version is not less than 2.2. You can install it with the following command:

pip3 install -U django>=2.2
pywebio.platform.django.webio_view(applications, cdn=True, session_expire_seconds=None, session_cleanup_interval=None, allowed_origins=None, check_origin=None)[source]

Get the view function for running PyWebIO applications in Django. The view communicates with the browser by HTTP protocol.

The arguments of webio_view() have the same meaning as for pywebio.platform.flask.webio_view()

pywebio.platform.django.wsgi_app(applications, cdn=True, static_dir=None, allowed_origins=None, check_origin=None, session_expire_seconds=None, session_cleanup_interval=None, debug=False, max_payload_size='200M', **django_options)[source]

Get the Django WSGI app for running PyWebIO applications.

The arguments of wsgi_app() have the same meaning as for pywebio.platform.django.start_server()

pywebio.platform.django.start_server(applications, port=8080, host='', cdn=True, static_dir=None, remote_access=False, allowed_origins=None, check_origin=None, session_expire_seconds=None, session_cleanup_interval=None, debug=False, max_payload_size='200M', **django_options)[source]

Start a Django server to provide the PyWebIO application as a web service.

Parameters
  • debug (bool) – Django debug mode. See Django doc for more detail.

  • django_options – Additional settings to django server. For details, please refer: https://docs.djangoproject.com/en/3.0/ref/settings/ . Among them, DEBUG, ALLOWED_HOSTS, ROOT_URLCONF, SECRET_KEY are set by PyWebIO and cannot be specified in django_options.

The rest arguments of start_server() have the same meaning as for pywebio.platform.flask.start_server()

aiohttp support

When using the aiohttp as PyWebIO backend server, you need to install aiohttp by yourself and make sure the version is not less than 3.1. You can install it with the following command:

pip3 install -U aiohttp>=3.1
pywebio.platform.aiohttp.webio_handler(applications, cdn=True, allowed_origins=None, check_origin=None, websocket_settings=None)[source]

Get the Request Handler coroutine for running PyWebIO applications in aiohttp. The handler communicates with the browser by WebSocket protocol.

The arguments of webio_handler() have the same meaning as for pywebio.platform.aiohttp.start_server()

Returns

aiohttp Request Handler

pywebio.platform.aiohttp.start_server(applications, port=0, host='', debug=False, cdn=True, static_dir=None, remote_access=False, allowed_origins=None, check_origin=None, auto_open_webbrowser=False, websocket_settings=None, **aiohttp_settings)[source]

Start a aiohttp server to provide the PyWebIO application as a web service.

Parameters

The rest arguments of start_server() have the same meaning as for pywebio.platform.tornado.start_server()

FastAPI/Starlette support

When using the FastAPI/Starlette as PyWebIO backend server, you need to install fastapi or starlette by yourself. Also other dependency packages are required. You can install them with the following command:

pip3 install -U fastapi starlette uvicorn aiofiles websockets
pywebio.platform.fastapi.webio_routes(applications, cdn=True, allowed_origins=None, check_origin=None)[source]

Get the FastAPI/Starlette routes for running PyWebIO applications.

The API communicates with the browser using WebSocket protocol.

The arguments of webio_routes() have the same meaning as for pywebio.platform.fastapi.start_server()

New in version 1.3.

Returns

FastAPI/Starlette routes

pywebio.platform.fastapi.asgi_app(applications, cdn=True, static_dir=None, debug=False, allowed_origins=None, check_origin=None)[source]

Get the starlette/Fastapi ASGI app for running PyWebIO applications.

Use pywebio.platform.fastapi.webio_routes() if you prefer handling static files yourself.

The arguments of asgi_app() have the same meaning as for pywebio.platform.fastapi.start_server()

Example

To be used with FastAPI.mount() to include pywebio as a subapp into an existing Starlette/FastAPI application:

from fastapi import FastAPI
from pywebio.platform.fastapi import asgi_app
from pywebio.output import put_text
app = FastAPI()
subapp = asgi_app(lambda: put_text("hello from pywebio"))
app.mount("/pywebio", subapp)
Returns

Starlette/Fastapi ASGI app

New in version 1.3.

pywebio.platform.fastapi.start_server(applications, port=0, host='', cdn=True, static_dir=None, remote_access=False, debug=False, allowed_origins=None, check_origin=None, auto_open_webbrowser=False, **uvicorn_settings)[source]

Start a FastAPI/Starlette server using uvicorn to provide the PyWebIO application as a web service.

Parameters
  • debug (bool) – Boolean indicating if debug tracebacks should be returned on errors.

  • uvicorn_settings – Additional keyword arguments passed to uvicorn.run(). For details, please refer: https://www.uvicorn.org/settings/

The rest arguments of start_server() have the same meaning as for pywebio.platform.tornado.start_server()

New in version 1.3.

Other

pywebio.config(*, title=None, description=None, js_code=None, js_file=[], css_style=None, css_file=[])[source]

PyWebIO application configuration

Parameters
  • title (str) – Application title

  • description (str) – Application description

  • js_code (str) – The javascript code that you want to inject to page.

  • js_file (str/list) – The javascript files that inject to page, can be a URL in str or a list of it.

  • css_style (str) – The CSS style that you want to inject to page.

  • css_file (str/list) – The CSS files that inject to page, can be a URL in str or a list of it.

config() can be used in 2 ways: direct call and decorator. If you call config() directly, the configuration will be global. If you use config() as decorator, the configuration will only work on single PyWebIO application function.

config(title="My application")

@config(css_style="* { color:red }")
def app():
    put_text("hello PyWebIO")

title and description are used for SEO, which are provided when indexed by search engines. If no title and description set for a PyWebIO application function, the docstring of the function will be used as title and description by default:

def app():
    """Application title

    Application description...
    (A empty line is used to separate the description and title)
    """
    pass

The above code is equal to:

@config(title="Application title", description="Application description...")
def app():
    pass

New in version 1.4.

pywebio.platform.run_event_loop(debug=False)[source]

run asyncio event loop

See also: Integration coroutine-based session with Web framework

Parameters

debug – Set the debug mode of the event loop. See also: https://docs.python.org/3/library/asyncio-dev.html#asyncio-debug-mode