当前位置: 首页 > news >正文

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

pkzLkTI.png

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&#xff0c;偶然看到一个很有意思的项目&#xff1a;PyWebIo。 这是一个 Python 第三方库&#xff0c;可以只用 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字符串函数总结 链表链表和链表节点的实现链表节点&#xff08;list…...

ARM 汇编语言基础

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

c语言小知识点小计

c语言小知识点小计 1、运算符的优先级 运算符的优先级是和指针解引用*的优先级相同的&#xff0c;但在代码运行中执行顺序是从后往前的。因此下面代码 int a[10] {1,2,3,4}; int* arr a; printf("%d",*arr);//访问的值是2 //注意&#xff1a;printf("%d&qu…...

《C#面向语言版本编程》C# 13 中的新增功能

将C#语言版本升级为预览版 C# 13 包括一些新增功能。 可以使用最新的 Visual Studio 2022 版本或 .NET 9 预览版 SDK 尝试这些功能。若想在.NET项目中尝试使用C#的最新预览版特性&#xff0c;可以按照以下步骤来升级你的项目语言版本&#xff1a; .打开项目文件&#xff1a; 找…...

0成本通过Hugo和GitHub Pages搭建博客

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

Ollama 可以玩 GLM4和CodeGeeX4了

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

浅析C++指针与引用的关系

前言&#xff1a; 在实践中指针与引用相辅相成&#xff0c;功能相互叠加&#xff0c;但各有各的特点&#xff0c;互相不可替代&#xff01;&#xff01;&#xff01;...

Python面试宝典第31题:字符串反转

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

【深入理解SpringCloud微服务】深入理解微服务中的远程调用,并手写一个微服务RPC框架

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

数据结构----二叉树

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

通过python管理mysql

打开防火墙端口&#xff1a; 使用 firewall-cmd 命令在防火墙的 public 区域中永久添加 TCP 端口 7500&#xff08;FRP 控制台面板端口&#xff09;、7000&#xff08;FRP 服务端端口&#xff09;以及端口范围 6000-6100&#xff08;一组客户端端口&#xff09;。这些端口是 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 : ** 名称&#xff1a;service-mysql 端口 &#xff1a;3306:3306 镜像&#xff1a;mysql:8.0 环境变量&#xff1a; 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的软件包都是从哪里来的&#xff1f;是从哪里能下载到这些软件包&#xff1f; 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&#xff0c;CCS是密码学领域的顶会。作者是来自加拿大的University of Waterloo。文章对大语言模型像GPT和LLM等大语言模型实现了零知识可验证执行&#xff0c;但不涉及零知识可验证训练。个人觉得…...

vscode插件中的图标怎么设置

首先在ts文件目录下和package.json同级的目录下加入一张图片&#xff0c;后缀是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数据库中的一个特殊存储区域&#xff0c;用于集中存放备份和恢复数据库所需的所有文件&#xff0c;包括归档日志和闪回日志。这个区域可以帮助数据库在遇到介质故障时进行完全恢复。通过将备份数…...

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…...

TDengine 快速体验(Docker 镜像方式)

简介 TDengine 可以通过安装包、Docker 镜像 及云服务快速体验 TDengine 的功能&#xff0c;本节首先介绍如何通过 Docker 快速体验 TDengine&#xff0c;然后介绍如何在 Docker 环境下体验 TDengine 的写入和查询功能。如果你不熟悉 Docker&#xff0c;请使用 安装包的方式快…...

相机Camera日志实例分析之二:相机Camx【专业模式开启直方图拍照】单帧流程日志详解

【关注我&#xff0c;后续持续新增专题博文&#xff0c;谢谢&#xff01;&#xff01;&#xff01;】 上一篇我们讲了&#xff1a; 这一篇我们开始讲&#xff1a; 目录 一、场景操作步骤 二、日志基础关键字分级如下 三、场景日志如下&#xff1a; 一、场景操作步骤 操作步…...

在rocky linux 9.5上在线安装 docker

前面是指南&#xff0c;后面是日志 sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo sudo dnf install docker-ce docker-ce-cli containerd.io -y docker version sudo systemctl start docker sudo systemctl status docker …...

spring:实例工厂方法获取bean

spring处理使用静态工厂方法获取bean实例&#xff0c;也可以通过实例工厂方法获取bean实例。 实例工厂方法步骤如下&#xff1a; 定义实例工厂类&#xff08;Java代码&#xff09;&#xff0c;定义实例工厂&#xff08;xml&#xff09;&#xff0c;定义调用实例工厂&#xff…...

苍穹外卖--缓存菜品

1.问题说明 用户端小程序展示的菜品数据都是通过查询数据库获得&#xff0c;如果用户端访问量比较大&#xff0c;数据库访问压力随之增大 2.实现思路 通过Redis来缓存菜品数据&#xff0c;减少数据库查询操作。 缓存逻辑分析&#xff1a; ①每个分类下的菜品保持一份缓存数据…...

智能仓储的未来:自动化、AI与数据分析如何重塑物流中心

当仓库学会“思考”&#xff0c;物流的终极形态正在诞生 想象这样的场景&#xff1a; 凌晨3点&#xff0c;某物流中心灯火通明却空无一人。AGV机器人集群根据实时订单动态规划路径&#xff1b;AI视觉系统在0.1秒内扫描包裹信息&#xff1b;数字孪生平台正模拟次日峰值流量压力…...

Android Bitmap治理全解析:从加载优化到泄漏防控的全生命周期管理

引言 Bitmap&#xff08;位图&#xff09;是Android应用内存占用的“头号杀手”。一张1080P&#xff08;1920x1080&#xff09;的图片以ARGB_8888格式加载时&#xff0c;内存占用高达8MB&#xff08;192010804字节&#xff09;。据统计&#xff0c;超过60%的应用OOM崩溃与Bitm…...

大学生职业发展与就业创业指导教学评价

这里是引用 作为软工2203/2204班的学生&#xff0c;我们非常感谢您在《大学生职业发展与就业创业指导》课程中的悉心教导。这门课程对我们即将面临实习和就业的工科学生来说至关重要&#xff0c;而您认真负责的教学态度&#xff0c;让课程的每一部分都充满了实用价值。 尤其让我…...

3-11单元格区域边界定位(End属性)学习笔记

返回一个Range 对象&#xff0c;只读。该对象代表包含源区域的区域上端下端左端右端的最后一个单元格。等同于按键 End 向上键(End(xlUp))、End向下键(End(xlDown))、End向左键(End(xlToLeft)End向右键(End(xlToRight)) 注意&#xff1a;它移动的位置必须是相连的有内容的单元格…...