如果你接触过Web开发,你可能对接下来描述的PyWebIO的用法感到不太习惯,不同于传统Web开发的后端实现接口、前端进行展示交互的模式,在PyWebIO中,所有的逻辑都通过编写Python代码实现。
你可以按照编写控制台程序的逻辑编写PyWebIO应用,只不过这里的终端变成了浏览器。通过PyWebIO提供的命令式API,你可以简单地调用 put_text() 、 put_image() 、 put_table() 等函数输出文本、图片、表格等内容到浏览器,也可以调用 input() 、 select() 、 file_upload() 等函数在浏览器上显示不同表单来接收用户的输入。此外PyWebIO中还提供了点击事件、布局等支持,让你可以使用最少的代码完成与用户的交互,并尽可能提供良好的用户体验。
This user guide introduces you the most of the features of PyWebIO. There is a demo link at the top right of the example codes in this document, where you can run the example code online and see what happens. Also, the PyWebIO Playground is a good place to write, run and share your PyWebIO code online.
输入
输入函数都定义在 pywebio.input 模块中,可以使用 from pywebio.input import * 引入。
调用输入函数会在浏览器上弹出一个输入表单来获取输入。PyWebIO的输入函数是阻塞式的(和Python内置的 input 一样),在表单被成功提交之前,输入函数不会返回。
基本输入
首先是一些基本类型的输入。
文本输入:
age = input("How old are you?", type=NUMBER)
这样一行代码的效果为:浏览器会弹出一个文本输入框来获取输入,在用户完成输入将表单提交后,函数返回用户输入的值。
下面是一些其他类型的输入函数:
age = input("How old are you?", type=NUMBER)
# Password input
password = input("Input password", type=PASSWORD)
# Drop-down selection
gift = select('Which gift you want?', ['keyboard', 'ipad'])
# Checkbox
agree = checkbox("User Term", options=['I agree to terms and conditions'])
# Single choice
answer = radio("Choose one", options=['A', 'B', 'C', 'D'])
# Multi-line text input
text = textarea('Text Area', rows=3, placeholder='Some text')
# File Upload
img = file_upload("Select a image:", accept="image/*")
输入和输出数字
from pywebio.input import input, NUMBER
from pywebio.output import put_text
age = input("请输入您的年龄:", type=NUMBER)
put_text('您输入的年龄是%d' % (age,))
输入和输出密码
from pywebio.input import input, PASSWORD
from pywebio.output import put_text
password = input("please input your password:", type=PASSWORD)
put_text('the password is %s' % (password,))
录入下拉框类型的数据
from pywebio.input import select
from pywebio.output import put_text
language = select("which language do you like?",
["Python", "Golang", "JavaScript", "Rust"])
put_text('you like %s' % (language,))
输入多选框类型的数据
from pywebio.input import checkbox
from pywebio.output import put_text
ck_value = checkbox(
"User term",
["I agree to terms and conditions"]
)
print(ck_value)
put_text('you like %s' % (ck_value,))
输入单选按钮值
from pywebio.input import radio
from pywebio.output import put_text
ck_value = radio(
"Choose one",
["A", "B", "C", "D"]
)
print(ck_value)
put_text('ck_value = %s' % (ck_value,))
输入多行文本
from pywebio.input import textarea
from pywebio.output import put_text
value = textarea(
"Text area",
rows = 3,
placeholder= "Please enter some text",
)
put_text('value = %s' % (value,))
上传图片和保存图片
from pywebio.input import file_upload
from pywebio.output import put_text
value = file_upload(
"choose file",
accept="image/*",
)
print(value, type(value))
# save img
filename = value.get("filename")
with open(filename,"wb") as f:
f.write(value.get("content"))
put_text('value = %s' % (filename,))