4,809
stars
+0+0+-6
384
forks
53
watchers
67
prs
251
issues
0
releases
–
discussions
README
PyWebIO
Write interactive web app in script way.
%3D%203.5.2-brightgreen" alt="Python Version"
[Document] | [Demos] | [Playground] | [Why PyWebIO?]
English | 中文
PyWebIO提供了一系列命令式的交互函数来在浏览器上获取用户输入和进行输出,将浏览器变成了一个“富文本终端”,可以用于构建简单的Web应用或基于浏览器的GUI应用。
PyWebIO还可以方便地整合进现有的Web服务,让你不需要编写HTML和JS代码,就可以构建出具有良好可用性的应用。
功能特性:
- 使用同步而不是基于回调的方式获取输入,代码编写逻辑更自然
- 非声明式布局,布局方式简单高效
- 代码侵入性小,旧脚本代码仅需修改输入输出逻辑便可改造为Web服务
- 支持整合到现有的Web服务,目前支持与Flask、Django、Tornado、aiohttp、FastAPI框架集成
- 同时支持基于线程的执行模型和基于协程的执行模型
- 支持结合第三方库实现数据可视化
Installation
稳定版安装:
bash
pip3 install -U pywebio
开发版安装:
bash
pip3 install -U https://github.com/pywebio/PyWebIO/archive/dev-release.zip
系统要求: PyWebIO要求 Python 版本在 3.5.2 及以上
Quickstart
Hello, world
这是一个使用PyWebIO计算 BMI指数 的脚本:
python
from pywebio.input import input, FLOAT
from pywebio.output import put_text
def bmi():
height = input("请输入你的身高(cm):", type=FLOAT)
weight = input("请输入你的体重(kg):", type=FLOAT)
BMI = weight / (height / 100) 2
top_status = [(14.9, '极瘦'), (18.4, '偏瘦'),
(22.9, '正常'), (27.5, '过重'),
(40.0, '肥胖'), (float('inf'), '非常肥胖')]
for top, status in top_status:
if BMI
作为Web服务提供
上文BMI程序会在计算完毕后立刻退出,可以使用 pywebio.start_server() 将 bmi() 函数作为Web服务提供:
python
from pywebio import start_server
from pywebio.input import input, FLOAT
from pywebio.output import put_text
def bmi(): bmi() 函数内容不变
...
if __name__ == '__main__':
start_server(bmi, port=80)
与现有Web框架整合
Tornado应用整合:仅需在现有的Tornado应用中添加一个 RequestHandler ,就可以将PyWebIO应用整合进Tornado Web服务中
python
import tornado.ioloop
import tornado.web
from pywebio.platform.tornado import webio_handler
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
(r"/bmi", webio_handler(bmi)), bmi 即为上文计算BMI指数的函数
])
application.listen(port=80, address='localhost')
tornado.ioloop.IOLoop.current().start()
在 http://localhost/bmi 页面上就可以计算BMI了。
与其他Web框架整合请见文档
Demos
- 基本demo : 包含PyWebIO基本输入输出演示和使用PyWebIO编写的小应用
- 数据可视化demo : 使用 bokeh、plotly、pyecharts 等库进行数据可视化
Links
使用手册和实现文档见 pywebio.readthedocs.io
PyWebIO Playground: 在线编辑、运行和分享PyWebIO代码