【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数据库中的一个特殊存储区域,用于集中存放备份和恢复数据库所需的所有文件,包括归档日志和闪回日志。这个区域可以帮助数据库在遇到介质故障时进行完全恢复。通过将备份数…...

获取客户端真实IP
出于安全考虑,近期在处理一个记录用户真实IP的需求。本来以为很简单,后来发现没有本来以为的简单。这里主要备忘下,如果服务器处于端口回流(hairpin NAT),keepalived,nginx之后,如何取得客户端的…...

韩式告白土味情话-柯桥生活韩语学习零基础入门教学
你们韩国人别太会告白了! 1、너 얼굴에 뭐가 조금 묻었어! 你的脸上有点5376东西! 뭐가 조금 묻었1585757는데? 有点什么? 이쁨이 조금 묻었네. 有点漂亮。 2、돌잡이 때 뭐 잡았어요? 你抓周的时候抓了什么? 쌀 잡았…...

Linux安全与高级应用(一)深入探讨Linux安全与高级应用
文章目录 深入探讨Linux安全与高级应用引言目录一、Linux安全与应用概述1.1 Linux的应用现状1.2 Linux的安全需求 二、构建LAMP企业网站平台2.1 LAMP平台简介2.2 安装和配置Apache服务器2.2.1 安装Apache2.2.2 配置Apache 2.3 安装和管理MySQL数据库2.3.1 安装MySQL2.3.2 配置M…...

【nginx 第二篇章】各个环境安装 nginx
一、Windows环境安装 1、下载 Nginx 访问Nginx官网(http://nginx.org/en/download.html)下载稳定版本的 Nginx 压缩包,如 nginx-1.xx.x.zip。下载后解压到指定的目录,例如 D:\nginx。 2、启动 Nginx 直接双击解压目录下的 ngi…...

在Spring Boot和MyBatis-Plus项目中,常见的错误及其解决方法2.0
1. org.springframework.beans.factory.BeanCreationException: Error creating bean with name requestMappingHandlerMapping 现象 在创建bean时发生错误,通常是因为存在重复的URL映射。 解决方法 检查所有控制器方法上的URL映射注解,确保没有重复…...

招聘信息数据清洗
文章目录 前言代码示例如下 前言 相关知识 为了完成本关任务,你需要掌握: 1.Spark 清洗数据的相关方法, 2.空值列怎么删除; 3.怎么数据切分才能达到想要的数据。 Spark清洗数据相关方法 一、将含有空值的数据删除 1.将含有空值的数据删除&a…...

机器学习——支持向量机(SVM)(1)
目录 一、认识SVM 1. 基本介绍 2. 支持向量机分类器目标 二、线性SVM分类原理(求解损失) 三、重要参数 1. kernel(核函数) 2 .C(硬间隔与软间隔) 四、sklearn中的支持向量机(自查&#…...

Elastic Observability 8.15:AI 助手、OTel 和日志质量增强功能
作者:来自 Elastic Alex Fedotyev, Tom Grabowski, Vinay Chandrasekhar, Miguel Luna Elastic Observability 8.15 宣布了几个关键功能: 新的和增强的原生 OpenTelemetry 功能: OpenTelemetry Collector 的 Elastic 分发:此版本…...

Unity3D ECS架构的优缺点详解
前言 Unity3D作为一款强大的游戏开发引擎,近年来在性能优化和架构设计上不断进化,其中ECS(Entity-Component-System)架构的引入是其重要的里程碑之一。ECS架构通过重新定义游戏对象的组织和处理方式,为开发者带来了诸…...

理解Go语言中多种并发模式
Go 的同步原语使实现高效的并发程序成为可能,并且选择合适的同步原语和并发模式可以更加容易地实现并发的可能,减少错误的发生。这里谈论的并发模式是只在 Go 语言中常见的并发的“套路” ,一种可解决某一类通用场景和问题的惯用方法。 1. 并发模式概述 我们先来回顾下同步…...