【Python】PyWebIO 初体验:用 Python 写网页
目录
- 前言
- 1 使用方法
- 1.1 安装 Pywebio
- 1.2 输出内容
- 1.3 输入内容
- 2 示例程序
- 2.1 BMI 计算器
- 2.2 Markdown 编辑器
- 2.3 聊天室
- 2.4 五子棋
前言
前两天正在逛 Github,偶然看到一个很有意思的项目:PyWebIo。
这是一个 Python 第三方库,可以只用 Python 语言写出一个网页,而且支持 Flask,Django,Tornado 等 web 框架。
甚至,它可以支持数据可视化图表的绘制,还提供了一行函数渲染 Markdown 文本。
那么话不多说,正片开始——
仓库地址:https://github.com/pywebio/PyWebIO
1 使用方法
1.1 安装 Pywebio
打开 CMD,在里面输入以下代码:
pip install pywebio
如果速度太慢,建议使用国内镜像:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pywebio
1.2 输出内容
put_text()
输出文字put_table()
输出表格put_markdown()
输出 markdown 内容put_file()
输出文件下载链接put_image()
输出图片put_button()
输出按钮
请看示例程序:
from pywebio.output import *def main():# 文本输出put_text("Hello world!")# 表格输出put_table([['商品', '价格'],['苹果', '5.5'],['香蕉', '7'],])# Markdown输出put_markdown('~~删除线~~')# 文件输出put_file('hello_word.txt', b'hello word!')if __name__ == '__main__':main()
1.3 输入内容
input()
和 python 一样的函数欸
from pywebio.input import *def main():name = input("请输入你的名字:")if __name__ == '__main__':main()
2 示例程序
这些都是官方给出的实例,代码都不到 100 行!
官方项目地址:https://pywebio-demos.pywebio.online/
2.1 BMI 计算器
from pywebio.input import input, FLOAT
from pywebio.output import put_textdef bmi():height = input("Your Height(cm):", type=FLOAT)weight = input("Your Weight(kg):", type=FLOAT)BMI = weight / (height / 100) ** 2top_status = [(14.9, 'Severely underweight'), (18.4, 'Underweight'),(22.9, 'Normal'), (27.5, 'Overweight'),(40.0, 'Moderately obese'), (float('inf'), 'Severely obese')]for top, status in top_status:if BMI <= top:put_text('Your BMI: %.1f, category: %s' % (BMI, status))breakif __name__ == '__main__':bmi()
2.2 Markdown 编辑器
from pywebio import start_serverfrom pywebio.output import *
from pywebio.pin import *
from pywebio.session import set_env, downloaddef main():"""Markdown Previewer"""set_env(output_animation=False)put_markdown("""# Markdown Live PreviewThe online markdown editor with live preview. The source code of this application is [here](https://github.com/wang0618/PyWebIO/blob/dev/demos/markdown_previewer.py).## Write your Markdown""")put_textarea('md_text', rows=18, code={'mode': 'markdown'})put_buttons(['Download content'], lambda _: download('saved.md', pin.md_text.encode('utf8')), small=True)put_markdown('## Preview')while True:change_detail = pin_wait_change('md_text')with use_scope('md', clear=True):put_markdown(change_detail['value'], sanitize=False)if __name__ == '__main__':start_server(main, port=8080, debug=True)
2.3 聊天室
import asynciofrom pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import defer_call, info as session_info, run_asyncMAX_MESSAGES_CNT = 10 ** 4chat_msgs = [] # The chat message history. The item is (name, message content)
online_users = set()def t(eng, chinese):"""return English or Chinese text according to the user's browser language"""return chinese if 'zh' in session_info.user_language else engasync def refresh_msg(my_name):"""send new message to current session"""global chat_msgslast_idx = len(chat_msgs)while True:await asyncio.sleep(0.5)for m in chat_msgs[last_idx:]:if m[0] != my_name: # only refresh message that not sent by current userput_markdown('`%s`: %s' % m, sanitize=True, scope='msg-box')# remove expired messageif len(chat_msgs) > MAX_MESSAGES_CNT:chat_msgs = chat_msgs[len(chat_msgs) // 2:]last_idx = len(chat_msgs)async def main():"""PyWebIO chat roomYou can chat with everyone currently online."""global chat_msgsput_markdown(t("## PyWebIO chat room\nWelcome to the chat room, you can chat with all the people currently online. You can open this page in multiple tabs of your browser to simulate a multi-user environment. This application uses less than 90 lines of code, the source code is [here](https://github.com/wang0618/PyWebIO/blob/dev/demos/chat_room.py)", "## PyWebIO聊天室\n欢迎来到聊天室,你可以和当前所有在线的人聊天。你可以在浏览器的多个标签页中打开本页面来测试聊天效果。本应用使用不到90行代码实现,源代码[链接](https://github.com/wang0618/PyWebIO/blob/dev/demos/chat_room.py)"))put_scrollable(put_scope('msg-box'), height=300, keep_bottom=True)nickname = await input(t("Your nickname", "请输入你的昵称"), required=True, validate=lambda n: t('This name is already been used', '昵称已被使用') if n in online_users or n == '📢' else None)online_users.add(nickname)chat_msgs.append(('📢', '`%s` joins the room. %s users currently online' % (nickname, len(online_users))))put_markdown('`📢`: `%s` join the room. %s users currently online' % (nickname, len(online_users)), sanitize=True, scope='msg-box')@defer_calldef on_close():online_users.remove(nickname)chat_msgs.append(('📢', '`%s` leaves the room. %s users currently online' % (nickname, len(online_users))))refresh_task = run_async(refresh_msg(nickname))while True:data = await input_group(t('Send message', '发送消息'), [input(name='msg', help_text=t('Message content supports inline Markdown syntax', '消息内容支持行内Markdown语法')),actions(name='cmd', buttons=[t('Send', '发送'), t('Multiline Input', '多行输入'), {'label': t('Exit', '退出'), 'type': 'cancel'}])], validate=lambda d: ('msg', 'Message content cannot be empty') if d['cmd'] == t('Send', '发送') and not d['msg'] else None)if data is None:breakif data['cmd'] == t('Multiline Input', '多行输入'):data['msg'] = '\n' + await textarea('Message content', help_text=t('Message content supports Markdown syntax', '消息内容支持Markdown语法'))put_markdown('`%s`: %s' % (nickname, data['msg']), sanitize=True, scope='msg-box')chat_msgs.append((nickname, data['msg']))refresh_task.close()toast("You have left the chat room")if __name__ == '__main__':start_server(main, debug=True)
2.4 五子棋
import timefrom pywebio import session, start_server
from pywebio.output import *goboard_size = 15
# -1 -> none, 0 -> black, 1 -> white
goboard = [[-1] * goboard_sizefor _ in range(goboard_size)
]def winner(): # return winner piece, return None if no winnerfor x in range(2, goboard_size - 2):for y in range(2, goboard_size - 2):# check if (x,y) is the win centerif goboard[x][y] != -1 and any([all(goboard[x][y] == goboard[m][n] for m, n in [(x - 2, y), (x - 1, y), (x + 1, y), (x + 2, y)]),all(goboard[x][y] == goboard[m][n] for m, n in [(x, y - 2), (x, y - 1), (x, y + 1), (x, y + 2)]),all(goboard[x][y] == goboard[m][n] for m, n in [(x - 2, y - 2), (x - 1, y - 1), (x + 1, y + 1), (x + 2, y + 2)]),all(goboard[x][y] == goboard[m][n] for m, n in [(x - 2, y + 2), (x - 1, y + 1), (x + 1, y - 1), (x + 2, y - 2)]),]):return ['⚫', '⚪'][goboard[x][y]]session_id = 0 # auto incremented id for each session
current_turn = 0 # 0 for black, 1 for white
player_count = [0, 0] # count of player for two rolesdef main():"""Online Shared Gomoku GameA web based Gomoku (AKA GoBang, Five in a Row) game made with PyWebIO under 100 lines of Python code."""global session_id, current_turn, goboardif winner(): # The current game is over, reset gamegoboard = [[-1] * goboard_size for _ in range(goboard_size)]current_turn = 0my_turn = session_id % 2my_chess = ['⚫', '⚪'][my_turn]session_id += 1player_count[my_turn] += 1@session.defer_calldef player_exit():player_count[my_turn] -= 1session.set_env(output_animation=False)put_html("""<style> table th, table td { padding: 0px !important;} button {padding: .75rem!important; margin:0!important} </style>""") # Custom styles to make the board more beautifulput_markdown(f"""# Online Shared Gomoku GameAll online players are assigned to two groups (black and white) and share this game. You can open this page in multiple tabs of your browser to simulate multiple users. This application uses less than 100 lines of code, the source code is [here](https://github.com/wang0618/PyWebIO/blob/dev/demos/gomoku_game.py)Currently online player: {player_count[0]} for ⚫, {player_count[1]} for ⚪. Your role is {my_chess}.""")def set_stone(pos):global current_turnif current_turn != my_turn:toast("It's not your turn!!", color='error')returnx, y = posgoboard[x][y] = my_turncurrent_turn = (current_turn + 1) % 2@use_scope('goboard', clear=True)def show_goboard():table = [[put_buttons([dict(label=' ', value=(x, y), color='light')], onclick=set_stone) if cell == -1 else [' ⚫', ' ⚪'][cell]for y, cell in enumerate(row)]for x, row in enumerate(goboard)]put_table(table)show_goboard()while not winner():with use_scope('msg', clear=True):current_turn_copy = current_turnif current_turn_copy == my_turn:put_text("It's your turn!")else:put_row([put_text("Your opponent's turn, waiting... "), put_loading().style('width:1.5em; height:1.5em')], size='auto 1fr')while current_turn == current_turn_copy and not session.get_current_session().closed(): # wait for next movetime.sleep(0.2)show_goboard()with use_scope('msg', clear=True):put_text('Game over. The winner is %s!\nRefresh page to start a new round.' % winner())if __name__ == '__main__':start_server(main, debug=True, port=8080)
稍微试了试这个第三方库,感觉功能十分的强大。
不只是上面的项目,它还有不同风格,能绘制不同图表,集成web框架。
有了这个库,我们就可以轻松地将 Python 程序展示在网页上,也就是实现使用 Python 开发前端!
本文就到这里,如果喜欢的话别望点赞收藏!拜~
相关文章:

【Python】PyWebIO 初体验:用 Python 写网页
目录 前言1 使用方法1.1 安装 Pywebio1.2 输出内容1.3 输入内容 2 示例程序2.1 BMI 计算器2.2 Markdown 编辑器2.3 聊天室2.4 五子棋 前言 前两天正在逛 Github,偶然看到一个很有意思的项目:PyWebIo。 这是一个 Python 第三方库,可以只用 P…...

OrangePi AIpro学习3 —— vscode开发昇腾DVPP程序
目录 一、VScode配置 1.1 下载和安装 1.2 安装和配置需要的插件 二、构建项目 2.1 项目架构 2.2 解决代码高亮显示 2.3 测试编译 2.4 总结出最简单的代码 2.5 vscode报错找不到头文件解决方法 三、代码简单讲解 3.1 初始化部分 3.2 拷贝数据到NPU显存中 3.3 准备裁…...

redis的数据结构与对象
简单动态字符串 文章目录 简单动态字符串SDS的定义SDS的结构图示结构SDS字段解析SDS的特点 SDS和字符串的区别常数复杂度获取字符串的长度杜绝缓冲区的溢出减少修改字符串时的内存分配次数二进制安全兼容部分c字符串函数总结 链表链表和链表节点的实现链表节点(list…...

ARM 汇编语言基础
目录 汇编指令代码框架 汇编指令语法格式 数据处理指令 数据搬移指令 mov 示例 立即数的本质 立即数的特点 立即数的使用 算术运算指令 指令格式 add 普通的加法指令 adc 带进位的加法指令 跳转指令 Load/Store指令 状态寄存器指令 基础概念 C 语言与汇编指令的关…...

c语言小知识点小计
c语言小知识点小计 1、运算符的优先级 运算符的优先级是和指针解引用*的优先级相同的,但在代码运行中执行顺序是从后往前的。因此下面代码 int a[10] {1,2,3,4}; int* arr a; printf("%d",*arr);//访问的值是2 //注意:printf("%d&qu…...
《C#面向语言版本编程》C# 13 中的新增功能
将C#语言版本升级为预览版 C# 13 包括一些新增功能。 可以使用最新的 Visual Studio 2022 版本或 .NET 9 预览版 SDK 尝试这些功能。若想在.NET项目中尝试使用C#的最新预览版特性,可以按照以下步骤来升级你的项目语言版本: .打开项目文件: 找…...

0成本通过Hugo和GitHub Pages搭建博客
版权归作者所有,如有转发,请注明文章出处:https://cyrus-studio.github.io/blog/ 使用 Chocolatey 安装 Hugo Chocolatey 是一个 Windows 软件包管理器,使用 PowerShell 和 NuGet 作为基础。它可以自动化软件的安装、升级和卸载过…...

Ollama 可以玩 GLM4和CodeGeeX4了
最近这一两周看到不少互联网公司都已经开始秋招提前批了。 不同以往的是,当前职场环境已不再是那个双向奔赴时代了。求职者在变多,HC 在变少,岗位要求还更高了。 最近,我们又陆续整理了很多大厂的面试题,帮助一些球友…...

浅析C++指针与引用的关系
前言: 在实践中指针与引用相辅相成,功能相互叠加,但各有各的特点,互相不可替代!!!...

Python面试宝典第31题:字符串反转
题目 编写一个函数,其作用是将输入的字符串反转过来,输入字符串以字符数组s的形式给出。不要给另外的数组分配额外的空间,你必须原地修改输入数组,并使用O(1)的额外空间解决这一问题。备注:s[i]都是ASCII码表中的可打印…...

【深入理解SpringCloud微服务】深入理解微服务中的远程调用,并手写一个微服务RPC框架
【深入理解SpringCloud微服务】深入理解微服务中的远程调用,并手写一个微服务RPC框架 远程过程调用微服务中的RPC框架如何实现一个微服务中的RPC框架接口扫描生成代理对象代理对象处理逻辑 手写一个微服务RPC框架RPCClientEnableRPCClientMicroServiceRPCClientRegi…...

数据结构----二叉树
小编会一直更新数据结构相关方面的知识,使用的语言是Java,但是其中的逻辑和思路并不影响,如果感兴趣可以关注合集。 希望大家看完之后可以自己去手敲实现一遍,同时在最后我也列出一些基本和经典的题目,可以尝试做一下。…...

通过python管理mysql
打开防火墙端口: 使用 firewall-cmd 命令在防火墙的 public 区域中永久添加 TCP 端口 7500(FRP 控制台面板端口)、7000(FRP 服务端端口)以及端口范围 6000-6100(一组客户端端口)。这些端口是 FR…...
Run the OnlyOffice Java Spring demo project in local
Content 1.Download the sample project in java2.Run the project3.Test the example document 1.Download the sample project in java Link: download the sample code in official website document properties setting spring 项目所在的服务器 server. Address192.168…...

11. Rancher2.X部署多案例镜像
**部署springboot项目 : ** **部署中间件Mysql8.0 : ** 名称:service-mysql 端口 :3306:3306 镜像:mysql:8.0 环境变量: MYSQL_ROOT_PASSWORDxdclass.net168路径映射 /home/data/mysql/data /var/lib/mysql:rw /etc/localtime…...

探索Linux世界之Linux环境开发工具的使用
目录 一、yum -- Linux软件包管理器 1、什么是yum 2、yum的使用 2.1 yum一些经常见的操作 1.查看软件包 2. 安装软件包 3. 删除软件包 3、yum的周边知识 3.1 yum的软件包都是从哪里来的?是从哪里能下载到这些软件包? 3.2 yum的拓展软件源 二、…...

探索Spring Boot微服务架构的最佳实践
目录 引言 一、Spring Boot简介 二、微服务架构的关键要素 三、Spring Boot在微服务中的最佳实践 3.1 清晰的服务边界 3.2 自动化配置与依赖管理 3.3 服务注册与发现 3.4 配置管理 3.5 安全与认证 3.6 监控与日志 3.7 分布式事务 四、总结 引言 在当今快速迭代的软…...

[论文泛读]zkLLM: Zero Knowledge Proofs for Large Language models
文章目录 介绍实验数据实验数据1实验数据2实验数据3 介绍 这篇文章发在CCS2024,CCS是密码学领域的顶会。作者是来自加拿大的University of Waterloo。文章对大语言模型像GPT和LLM等大语言模型实现了零知识可验证执行,但不涉及零知识可验证训练。个人觉得…...

vscode插件中的图标怎么设置
首先在ts文件目录下和package.json同级的目录下加入一张图片,后缀是jpg、png、jpeg都可以。 然后package.json中加入该行 重新 vsce package即可 如果出现报错 The specified icon xxx/xxx/icon.jpg wasnt found in the extension. 那就是没有放正确文件夹的位…...
Study--Oracle-08-oracle数据库的闪回技术
一、闪回恢复区(Flash Recovery Area) 1、什么是闪回恢复区 闪回恢复区是Oracle数据库中的一个特殊存储区域,用于集中存放备份和恢复数据库所需的所有文件,包括归档日志和闪回日志。这个区域可以帮助数据库在遇到介质故障时进行完全恢复。通过将备份数…...

stm32G473的flash模式是单bank还是双bank?
今天突然有人stm32G473的flash模式是单bank还是双bank?由于时间太久,我真忘记了。搜搜发现,还真有人和我一样。见下面的链接:https://shequ.stmicroelectronics.cn/forum.php?modviewthread&tid644563 根据STM32G4系列参考手…...

练习(含atoi的模拟实现,自定义类型等练习)
一、结构体大小的计算及位段 (结构体大小计算及位段 详解请看:自定义类型:结构体进阶-CSDN博客) 1.在32位系统环境,编译选项为4字节对齐,那么sizeof(A)和sizeof(B)是多少? #pragma pack(4)st…...

SCAU期末笔记 - 数据分析与数据挖掘题库解析
这门怎么题库答案不全啊日 来简单学一下子来 一、选择题(可多选) 将原始数据进行集成、变换、维度规约、数值规约是在以下哪个步骤的任务?(C) A. 频繁模式挖掘 B.分类和预测 C.数据预处理 D.数据流挖掘 A. 频繁模式挖掘:专注于发现数据中…...

学习STC51单片机32(芯片为STC89C52RCRC)OLED显示屏2
每日一言 今天的每一份坚持,都是在为未来积攒底气。 案例:OLED显示一个A 这边观察到一个点,怎么雪花了就是都是乱七八糟的占满了屏幕。。 解释 : 如果代码里信号切换太快(比如 SDA 刚变,SCL 立刻变&#…...
Java多线程实现之Thread类深度解析
Java多线程实现之Thread类深度解析 一、多线程基础概念1.1 什么是线程1.2 多线程的优势1.3 Java多线程模型 二、Thread类的基本结构与构造函数2.1 Thread类的继承关系2.2 构造函数 三、创建和启动线程3.1 继承Thread类创建线程3.2 实现Runnable接口创建线程 四、Thread类的核心…...
重启Eureka集群中的节点,对已经注册的服务有什么影响
先看答案,如果正确地操作,重启Eureka集群中的节点,对已经注册的服务影响非常小,甚至可以做到无感知。 但如果操作不当,可能会引发短暂的服务发现问题。 下面我们从Eureka的核心工作原理来详细分析这个问题。 Eureka的…...

Yolov8 目标检测蒸馏学习记录
yolov8系列模型蒸馏基本流程,代码下载:这里本人提交了一个demo:djdll/Yolov8_Distillation: Yolov8轻量化_蒸馏代码实现 在轻量化模型设计中,**知识蒸馏(Knowledge Distillation)**被广泛应用,作为提升模型…...
JavaScript基础-API 和 Web API
在学习JavaScript的过程中,理解API(应用程序接口)和Web API的概念及其应用是非常重要的。这些工具极大地扩展了JavaScript的功能,使得开发者能够创建出功能丰富、交互性强的Web应用程序。本文将深入探讨JavaScript中的API与Web AP…...

如何更改默认 Crontab 编辑器 ?
在 Linux 领域中,crontab 是您可能经常遇到的一个术语。这个实用程序在类 unix 操作系统上可用,用于调度在预定义时间和间隔自动执行的任务。这对管理员和高级用户非常有益,允许他们自动执行各种系统任务。 编辑 Crontab 文件通常使用文本编…...

Golang——7、包与接口详解
包与接口详解 1、Golang包详解1.1、Golang中包的定义和介绍1.2、Golang包管理工具go mod1.3、Golang中自定义包1.4、Golang中使用第三包1.5、init函数 2、接口详解2.1、接口的定义2.2、空接口2.3、类型断言2.4、结构体值接收者和指针接收者实现接口的区别2.5、一个结构体实现多…...