当前位置: 首页 > 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;包括归档日志和闪回日志。这个区域可以帮助数据库在遇到介质故障时进行完全恢复。通过将备份数…...

【CSS position 属性】static、relative、fixed、absolute 、sticky详细介绍,多层嵌套定位示例

文章目录 ★ position 的五种类型及基本用法 ★ 一、position 属性概述 二、position 的五种类型详解(初学者版) 1. static(默认值) 2. relative(相对定位) 3. absolute(绝对定位) 4. fixed(固定定位) 5. sticky(粘性定位) 三、定位元素的层级关系(z-i…...

ardupilot 开发环境eclipse 中import 缺少C++

目录 文章目录 目录摘要1.修复过程摘要 本节主要解决ardupilot 开发环境eclipse 中import 缺少C++,无法导入ardupilot代码,会引起查看不方便的问题。如下图所示 1.修复过程 0.安装ubuntu 软件中自带的eclipse 1.打开eclipse—Help—install new software 2.在 Work with中…...

SpringTask-03.入门案例

一.入门案例 启动类&#xff1a; package com.sky;import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCach…...

宇树科技,改名了!

提到国内具身智能和机器人领域的代表企业&#xff0c;那宇树科技&#xff08;Unitree&#xff09;必须名列其榜。 最近&#xff0c;宇树科技的一项新变动消息在业界引发了不少关注和讨论&#xff0c;即&#xff1a; 宇树向其合作伙伴发布了一封公司名称变更函称&#xff0c;因…...

React核心概念:State是什么?如何用useState管理组件自己的数据?

系列回顾&#xff1a; 在上一篇《React入门第一步》中&#xff0c;我们已经成功创建并运行了第一个React项目。我们学会了用Vite初始化项目&#xff0c;并修改了App.jsx组件&#xff0c;让页面显示出我们想要的文字。但是&#xff0c;那个页面是“死”的&#xff0c;它只是静态…...

基于 HTTP 的单向流式通信协议SSE详解

SSE&#xff08;Server-Sent Events&#xff09;详解 &#x1f9e0; 什么是 SSE&#xff1f; SSE&#xff08;Server-Sent Events&#xff09; 是 HTML5 标准中定义的一种通信机制&#xff0c;它允许服务器主动将事件推送给客户端&#xff08;浏览器&#xff09;。与传统的 H…...

理想汽车5月交付40856辆,同比增长16.7%

6月1日&#xff0c;理想汽车官方宣布&#xff0c;5月交付新车40856辆&#xff0c;同比增长16.7%。截至2025年5月31日&#xff0c;理想汽车历史累计交付量为1301531辆。 官方表示&#xff0c;理想L系列智能焕新版在5月正式发布&#xff0c;全系产品力有显著的提升&#xff0c;每…...

解密鸿蒙系统的隐私护城河:从权限动态管控到生物数据加密的全链路防护

摘要 本文以健康管理应用为例&#xff0c;展示鸿蒙系统如何通过细粒度权限控制、动态权限授予、数据隔离和加密存储四大核心机制&#xff0c;实现复杂场景下的用户隐私保护。我们将通过完整的权限请求流程和敏感数据处理代码&#xff0c;演示鸿蒙系统如何平衡功能需求与隐私安…...

[学习笔记]使用git rebase做分支差异化同步

在一个.NET 项目中&#xff0c;使用了Volo.Abp库&#xff0c;但出于某种原因&#xff0c;需要源码调试&#xff0c;因此&#xff0c;使用源码方式集成的项目做了一个分支archive-abp-source 其中引用方式变更操作的提交为&#xff1a;7de53907 后续&#xff0c;在master分支中…...

使用MounRiver Studio Ⅱ软件写一个CH592F芯片的ADC采集程序,碰到的问题

MounRiver Studio Ⅱ 默认是不开启浮点计算的&#xff0c;所以有些浮点功能不能用&#xff0c;碰到问题是 while (1) {DelayMs (100);tmp Read_Temperature (0);sprintf (tempBuffer, "temp:%.2f\r\n", tmp); // 格式化温度值到字符串。使用%f要开启相应的…...