pywebio.platform — 应用部署

platform 模块提供了以不同方式部署PyWebIO应用的支持。

Directory Deploy

可以使用 path_deploy()path_deploy_http() 来从一个目录中部署PyWebIO应用。该目录下的python文件需要包含一个名为 main 的函数作为PyWebIO应用。服务端会根据用户访问的URL来确定需要加载的文件并从中读取PyWebIO应用来运行。

用户无法访问该目录下以下划线开始的文件和目录。

例如,给定如下文件结构:

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

三个python文件都含有 main PyWebIO应用函数。

如果使用以上路径调用 path_deploy() ,你可以通过 URL http://<host>:<port>/A/b` 来访问 b.py 文件中的PyWebIO应用。若文件在运行 path_deploy() 之后被修改,可以使用 reload URL参数来重载文件: http://<host>:<port>/A/b?reload

你还可以使用 pywebio-path-deploy 命令来启动一个和 path_deploy() 效果一样的server。关于命令的更多信息请查阅命令帮助: pywebio-path-deploy --help

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

从一个路径中部署PyWebIO应用

服务端使用WebSocket协议与浏览器进行通讯。

参数
  • base (str) – 用于加载PyWebIO应用的根目录

  • port (int) – 服务器监听的端口

  • host (str) – 服务绑定的地址

  • index (bool/callable) – 当请求一个文件夹时是否显示默认的索引页面,默认为 Trueindex 也可以为一个函数来自定义索引页面,其接收请求的文件夹路径作为参数,返回页面HTML字符串。你可以在文件夹中创建一个 index.py PyWebIO应用文件来重写文件夹的索引页。

  • static_dir (str) – 应用静态文件目录。目录下的文件可以通过 http://<host>:<port>/static/files 访问。例如 static_dir 路径下存在文件 A/B.jpg ,则其URL为 http://<host>:<port>/static/A/B.jpg

  • reconnect_timeout (int) – 客户端重连超时时间(秒)。客户端若意外与服务端断开连接,在 reconnect_timeout 秒内可以重新连接并自动恢复会话。

剩余参数的详细说明见 pywebio.platform.tornado.start_server() 的同名参数。

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

从一个路径中部署PyWebIO应用

服务端使用HTTP协议与浏览器进行通讯。

关于 path_deploy_http()base, port, host, index, static_dir 参数的详细说明见 pywebio.platform.path_deploy() 的同名参数。

剩余参数的详细说明见 pywebio.platform.tornado_http.start_server() 的同名参数。

Application Deploy

start_server() 函数可以启动一个Web服务器来将PyWebIO应用作为Web服务运行。

webio_handler()webio_view() 函数用于将PyWebIO应用整合到现有的Python Web项目中。

wsgi_app()asgi_app() 用于获取运行PyWebIO应用的 WSGI 或 ASGI app。很适合当你不想使用Web框架内置的server来启动服务的情况。比如,你想使用其他WSGI server来启动应用,或者你正在将应用部署到一些云环境中。目前仅在Flask、Django 和 FastApi后端中支持 wsgi_app() / asgi_app()

在 1.1 版更改: Added the cdn parameter in start_server(), webio_handler() and webio_view().

在 1.2 版更改: Added the static_dir parameter in start_server().

在 1.3 版更改: Added the wsgi_app() and asgi_app().

Tornado相关

服务端可以通过两种协议(WebSocket 和 HTTP)来与用户浏览器通信。

WebSocket

pywebio.platform.tornado.start_server(applications: Union[Callable[], None], List[Callable[], None]], Dict[str, Callable[], None]]], port: int = 0, host: str = '', debug: bool = False, cdn: Union[bool, str] = True, static_dir: Optional[str] = None, remote_access: bool = False, reconnect_timeout: int = 0, allowed_origins: Optional[List[str]] = None, check_origin: Optional[Callable[[str], bool]] = None, auto_open_webbrowser: bool = False, max_payload_size: Union[int, str] = '200M', **tornado_app_settings)[源代码]

启动一个 Tornado server 将PyWebIO应用作为Web服务提供。

Tornado server 使用WebSocket协议与浏览器进行通讯。

Tornado为PyWebIO应用的默认后端Server,可以直接使用 from pywebio import start_server 导入。

参数
  • applications (list/dict/callable) –

    PyWebIO应用. 可以是任务函数或者任务函数的字典或列表。详细用法参见 使用start_server()部署多应用

    任务函数为协程函数时,使用 基于协程的会话实现 ;任务函数为普通函数时,使用基于线程的会话实现。

  • port (int) – 服务监听的端口。设置为 0 时,表示自动选择可用端口。

  • host (str) – 服务绑定的地址。 host 可以是IP地址或者为hostname。如果为hostname,服务会监听所有与该hostname关联的IP地址。 通过设置 host 为空字符串或 None 来将服务绑定到所有可用的地址上。

  • debug (bool) – 是否开启Tornado Server的debug模式,开启后,代码发生修改后服务器会自动重启。 详情请参阅 tornado 文档

  • cdn (bool/str) – 是否从CDN加载前端静态资源,默认为 True 。支持传入自定义的URL来指定静态资源的部署地址

  • static_dir (str) – 应用静态文件目录。目录下的文件可以通过 http://<host>:<port>/static/files 访问。例如 static_dir 路径下存在文件 A/B.jpg ,则其URL为 http://<host>:<port>/static/A/B.jpg

  • remote_access (bool) – 是否开启远程接入的功能。开启后,你将得到一个你当前应用的临时公网访问地址,其他人可以通过此地址访问你的应用。

  • auto_open_webbrowser (bool) – 当服务启动后,是否自动打开浏览器来访问服务。(该操作需要操作系统支持)

  • reconnect_timeout (int) – 客户端重连超时时间(秒)。客户端若意外与服务端断开连接,在 reconnect_timeout 秒内可以重新连接并自动恢复会话。

  • allowed_origins (list) –

    除当前域名外,服务器还允许的请求的来源列表。来源包含协议、域名和端口部分,允许使用 Unix shell 风格的匹配模式:

    • * 为通配符

    • ? 匹配单个字符

    • [seq] 匹配seq中的任何字符

    • [!seq] 匹配任何不在seq中的字符

    比如 https://*.example.com*://*.example.com

    全部规则参见 Python文档

  • check_origin (callable) – 请求来源检查函数。接收请求来源(包含协议、域名和端口部分)字符串作为参数, 返回 True/False 指示服务器接受/拒绝该请求。若设置了 check_originallowed_origins 参数将被忽略

  • auto_open_webbrowser – 当服务启动后,是否自动打开浏览器来访问服务。(该操作需要操作系统支持)

  • max_payload_size (int/str) – Tornado Server可以接受的最大websocket消息的大小。超过 max_payload_size (默认 200MB) 的消息会被拒绝接受。 max_payload_size 可以是整形表示的字节数或以 K / M / G 结尾的字符串,比如: 500, '40K', '3M'

  • tornado_app_settings – 传递给 tornado.web.Application 构造函数的额外的关键字参数 可设置项参考: 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)[源代码]

获取在Tornado中运行PyWebIO应用的RequestHandler类。RequestHandler类基于WebSocket协议与浏览器进行通讯。

关于各参数的详细说明见 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)[源代码]

启动一个 Tornado server 将PyWebIO应用作为Web服务提供。

服务端使用HTTP协议与浏览器进行通讯。

参数
  • session_expire_seconds (int) – 会话过期时间,单位为秒(默认60秒)。若 session_expire_seconds 秒内没有收到客户端的请求,则认为会话过期。

  • session_cleanup_interval (int) – 会话清理间隔,单位为秒(默认12秒)。服务端会周期性清理过期的会话,释放会话占用的资源。

  • max_payload_size (int/str) – Tornado Server可以接受的最大单个HTTP请求的大小

剩余参数的详细说明见 pywebio.platform.tornado.start_server() 的同名参数。

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

获取在Tornado中运行PyWebIO应用的RequestHandler类。RequestHandler类基于HTTP协议与浏览器进行通讯。

关于各参数的详细说明见 pywebio.platform.tornado_http.start_server() 的同名参数。

1.2 新版功能.

Flask support

使用Flask后端作为PyWebIO应用Server时,需要您自行安装Flask,并确保版本大于等于 0.10 。 可通过以下命令安装:

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

获取在Flask中运行PyWebIO任务的视图函数。基于http请求与前端页面进行通讯

关于各参数的详细说明见 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')[源代码]

将PyWebIO应用转换为Flask WSGI 应用

关于各参数的详细说明见 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)[源代码]

启动一个 Flask server 将PyWebIO应用作为Web服务提供。

参数
  • session_expire_seconds (int) – 会话过期时间,单位为秒(默认600秒)。若 session_expire_seconds 秒内没有收到客户端的请求,则认为会话过期。

  • session_cleanup_interval (int) – 会话清理间隔,单位为秒(默认300秒)。服务端会周期性清理过期的会话,释放会话占用的资源。

  • debug (bool) – 是否开启Flask Server的debug模式,开启后,代码发生修改后服务器会自动重启。

  • max_payload_size (int/str) – Flask Server可以接受的最大单个HTTP请求的大小

  • flask_options – 传递给 flask.Flask.run 函数的额外的关键字参数 可设置项参考: https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.run

关于各参数的详细说明见 pywebio.platform.tornado.start_server() 的同名参数

Django support

使用Django后端作为PyWebIO应用Server时,需要您自行安装Django,并确保版本大于等于 2.2 。 可通过以下命令安装:

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

获取在django中运行PyWebIO任务的视图函数。 基于http请求与前端进行通讯

关于各参数的详细说明见 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)[源代码]

将PyWebIO应用转换为Django WSGI 应用

关于各参数的详细说明见 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)[源代码]

启动一个 Django server 将PyWebIO应用作为Web服务提供。

参数

剩余参数的详细说明见 pywebio.platform.flask.start_server() 的同名参数。

aiohttp support

使用aiohttp后端作为PyWebIO应用Server时,需要您自行安装aiohttp,并确保版本大于等于 3.1 。 可通过以下命令安装:

pip3 install -U aiohttp>=3.1
pywebio.platform.aiohttp.webio_handler(applications, cdn=True, reconnect_timeout=0, allowed_origins=None, check_origin=None, max_payload_size='200M', websocket_settings=None)[源代码]

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

返回

aiohttp Request Handler

pywebio.platform.aiohttp.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', websocket_settings=None, **aiohttp_settings)[源代码]

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

参数

剩余参数的详细说明见 pywebio.platform.tornado.start_server() 的同名参数。

FastAPI/Starlette support

当使用FastAPI/Starlette作为PyWebIO的后端server时,你需要手动安装 fastapistarlette ,另外还需要安装一些其他的依赖库,可以使用以下命令安装:

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

获取在FastAPI/Starlette中运行PyWebIO的路由组件。

服务端使用WebSocket协议与浏览器进行通讯。

关于各参数的详细说明见 pywebio.platform.fastapi.start_server() 的同名参数。

1.3 新版功能.

返回

FastAPI/Starlette routes

pywebio.platform.fastapi.asgi_app(applications, cdn=True, reconnect_timeout=0, static_dir=None, debug=False, allowed_origins=None, check_origin=None)[源代码]

将PyWebIO应用转换为starlette/Fastapi ASGI应用

如果你需要自己托管静态文件,请使用 pywebio.platform.fastapi.webio_routes()

关于各参数的详细说明见 pywebio.platform.fastapi.start_server() 的同名参数。

Example

FastAPI.mount() 一起使用以将 pywebio 作为子应用包含到现有的 Starlette/FastAPI 应用程序中:

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

1.3 新版功能.

pywebio.platform.fastapi.start_server(applications, port=0, host='', cdn=True, reconnect_timeout=0, static_dir=None, remote_access=False, debug=False, allowed_origins=None, check_origin=None, auto_open_webbrowser=False, max_payload_size='200M', **uvicorn_settings)[源代码]

启动一个 FastAPI/Starlette server 将PyWebIO应用作为Web服务提供。

参数
  • debug (bool) – 发生异常时是否打印调用栈。

  • uvicorn_settings – 传递给 uvicorn.run() 的额外关键字参数 可设置项参考: https://www.uvicorn.org/settings/

剩余参数的详细说明见 pywebio.platform.tornado.start_server() 的同名参数。

1.3 新版功能.

其他

pywebio.config(*, title=None, description=None, theme=None, js_code=None, js_file=[], css_style=None, css_file=[], manifest=True)[源代码]

PyWebIO应用配置

参数
  • title (str) – 应用标题

  • description (str) – 应用简介

  • theme (str) –

    主题设置。可用主题有: dark, sketchy, minty, yeti 。同样可以使用环境变量 PYWEBIO_THEME 来设置主题(有更高优先级)。

    主题预览

    Open Source Credits

    dark主题更改自 bootstrap-dark , sketchy, minty和yeti 主题来自 bootswatch

  • js_code (str) – 需要注入到页面上的Javascript代码

  • js_file (str/list) – 需要添加到页面上的Javascript脚本文件,可以是文件的URL或URL列表。

  • css_style (str) – 需要注入到页面上的CSS样式规则。

  • css_file (str/list) – 需要添加到页面上的CSS样式文件,可以是文件的URL或URL列表。

  • manifest (bool/dict) –

    Web application manifest configuration. This feature allows you to add a shortcut to the home screen of your mobile device, and launch the app like a native app. If set to True, the default manifest will be used. You can also specify the manifest content in dict. If False, the manifest will be disabled.

    Note for icon configuration

    Currently, the icons field of the manifest is not supported. Instead, you can use the icon field to specify the icon url.

config() 可以通过两种方式使用:直接调用或作为装饰器使用。如果直接调用 config() ,将会作用于全局;如果使用装饰器,配置进将作用于被装饰的PyWebIO应用函数:

config(title="My application")  # global configuration

@config(css_style="* { color:red }")  # only works on this application
def app():
    put_text("hello PyWebIO")

注解

The configuration will affect all sessions

titledescription 被用来设置SEO(在被搜索引擎索引时提供的网页信息)。如果没有提供 titledescription ,PyWebIO默认会将任务函数的 函数注释 作为SEO信息:

def app():
    """应用标题

    应用简介...
    (应用简介和标题之间使用一个空行分隔)
    """
    pass

以上代码等价于:

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

1.4 新版功能.

在 1.5 版更改: add theme parameter

pywebio.platform.run_event_loop(debug=False)[源代码]

运行 asyncio 事件循环

See also: Integration coroutine-based session with Web framework

参数

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