【Python】PyWebIO 初体验:用 Python 写网页

news2024/9/22 7:24:02

目录

    • 前言
    • 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_text
  
def bmi():
    height = input("Your Height(cm):", type=FLOAT)
    weight = input("Your Weight(kg):", type=FLOAT)
  
    BMI = weight / (height / 100) ** 2
  
    top_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))
            break
  
if __name__ == '__main__':
    bmi()

2.2 Markdown 编辑器

from pywebio import start_server

from pywebio.output import *
from pywebio.pin import *
from pywebio.session import set_env, download


def main():
    """Markdown Previewer"""
    set_env(output_animation=False)

    put_markdown("""# Markdown Live Preview
    The 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 asyncio

from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import defer_call, info as session_info, run_async

MAX_MESSAGES_CNT = 10 ** 4

chat_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 eng


async def refresh_msg(my_name):
    """send new message to current session"""
    global chat_msgs
    last_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 user
                put_markdown('`%s`: %s' % m, sanitize=True, scope='msg-box')

        # remove expired message
        if len(chat_msgs) > MAX_MESSAGES_CNT:
            chat_msgs = chat_msgs[len(chat_msgs) // 2:]

        last_idx = len(chat_msgs)


async def main():
    """PyWebIO chat room

    You can chat with everyone currently online.
    """
    global chat_msgs

    put_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_call
    def 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:
            break
        if 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 time

from pywebio import session, start_server
from pywebio.output import *

goboard_size = 15
# -1 -> none, 0 -> black, 1 -> white
goboard = [
    [-1] * goboard_size
    for _ in range(goboard_size)
]


def winner():  # return winner piece, return None if no winner
    for x in range(2, goboard_size - 2):
        for y in range(2, goboard_size - 2):
            # check if (x,y) is the win center
            if 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 roles


def main():
    """Online Shared Gomoku Game

    A web based Gomoku (AKA GoBang, Five in a Row) game made with PyWebIO under 100 lines of Python code."""
    global session_id, current_turn, goboard
    if winner():  # The current game is over, reset game
        goboard = [[-1] * goboard_size for _ in range(goboard_size)]
        current_turn = 0

    my_turn = session_id % 2
    my_chess = ['⚫', '⚪'][my_turn]
    session_id += 1
    player_count[my_turn] += 1

    @session.defer_call
    def player_exit():
        player_count[my_turn] -= 1

    session.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 beautiful

    put_markdown(f"""# Online Shared Gomoku Game
    All 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_turn
        if current_turn != my_turn:
            toast("It's not your turn!!", color='error')
            return
        x, y = pos
        goboard[x][y] = my_turn
        current_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_turn
            if 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 move
                time.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 开发前端!

本文就到这里,如果喜欢的话别望点赞收藏!拜~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1997198.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

100 Exercises To Learn Rust 挑战!准备篇

公司内部的学习会非常活跃&#xff01;我也参与了Rust学习会&#xff0c;并且一直在研究rustlings。最近&#xff0c;我发现了一个类似于rustlings的新教程网站&#xff1a;Welcome - 100 Exercises To Learn Rust。 rustlings是基于Rust的权威官方文档《The Rust Programming…

汽车免拆诊断案例 | 2010款劳斯莱斯古斯特车中央信息显示屏提示传动系统故障

故障现象  一辆2010款劳斯莱斯古斯特车&#xff0c;搭载N74发动机&#xff0c;累计行驶里程约为11万km。车主反映&#xff0c;起动发动机后组合仪表和中央信息显示屏均提示传动系统故障。用故障检测仪检测&#xff0c;发现发动机控制模块2&#xff08;DME2&#xff09;中存储…

SmartBI拓展包二开入门开发

前言 新接到一个项目拓展包三开的需求&#xff0c;没有相关经验&#xff0c;学习开发&#xff0c;本文尝试通过简单的定位以及指导&#xff0c;确定修改点 SmartBI帮助文档-拓展包开发 登录 http://localhost:18080/smartbi/vision/index.jsp后台配置 上传拓展包&#xff0…

MySQL和Redis的数据一致性

MySQL和Redis的数据一致性 多线程环境下的涉及读写的缓存才会存在MySQL和Redis的数据不一致问题 先删除缓存再更新数据库再延时删除缓存 线程一删除缓存线程一更新数据线程二开始查数据如果第二步线程一更新数据延时&#xff0c;那么线程二会重新从数据库加载数据&#xff0…

超好用的windows系统工具PowerToys

文章目录 Github地址基本介绍使用 Github地址 PowerToys 基本介绍 是windows官方好用的工具箱&#xff0c;包括各种工具 使用 要带上win键 此工具安装后每次运行电脑自启动&#xff0c;桌面没有快捷方式&#xff0c;只能右下角 窗口在上效果演示&#xff0c;会被蓝线框到…

基于GeoTools使用JavaFx进行矢量数据可视化实战

目录 前言 一、JavaFx展示原理说明 二、GeoTools的Maven依赖问题 三、引入Geotools相关的资源包 四、创建JavaFx的Canvas实例 五、JavaFx的Scene和Node的绑定 六、总结 前言 众所周知&#xff0c;JavaFx是Java继Swing之后的又一款用于桌面应用的开发利器。当然&#xff0…

江科大/江协科技 STM32学习笔记P22

文章目录 AD单通道&AD多通道ADC基本结构和ADC有关的库函数AD单通道AD.cmain.c连续转换&#xff0c;非扫描模式的AD.c AD多通道AD.cmain.c AD单通道&AD多通道 ADC基本结构 第一步&#xff0c;开启RCC时钟&#xff0c;包括ADC和GPIO的时钟&#xff0c;ADCCLK的分频器也需…

openvidu私有化部署

openvidu私有化部署 简介 OpenVidu 是一个允许您实施实时应用程序的平台。您可以从头开始构建全新的 OpenVidu 应用程序&#xff0c;但将 OpenVidu 集成到您现有的应用程序中也非常容易。 OpenVidu 基于 WebRTC 技术&#xff0c;允许开发您可以想象的任何类型的用例&#xf…

回归预测|基于黏菌优化LightGBM的数据回归预测Matlab程序SMA-LightGBM 多特征输入单输出

回归预测|基于黏菌优化LightGBM的数据回归预测Matlab程序SMA-LightGBM 多特征输入单输出 文章目录 前言回归预测|基于黏菌优化LightGBM的数据回归预测Matlab程序 多特征输入单输出 SMA-LightGBM 一、SMA-LightGBM模型1. **LightGBM**2. **黏菌智能优化算法&#xff08;SMA&…

知识中台是什么?它如何实现高效知识管理?

引言 在信息化浪潮席卷全球的今天&#xff0c;企业面临的不仅是市场的激烈竞争&#xff0c;更是知识爆炸带来的管理挑战。如何在浩瀚的信息海洋中提炼出有价值的知识&#xff0c;并将其快速转化为企业的核心竞争力&#xff0c;成为了每个企业必须深思的问题。在此背景下&#…

二叉树的重要概念

前言&#xff1a; 二叉树是树形结构的一个重要类型&#xff0c;一般的树也可以转化成二叉树来解决问题。在数据结构的系统中&#xff0c;树形结构也是信息存储和遍历的重要实现&#xff0c;二叉树的最大特点就是一个根包含着左右子树的形式&#xff0c;许多具有层次关系的问题…

单元测试注解:@ContextConfiguration

ContextConfiguration注解 ContextConfiguration注解主要用于在‌Spring框架中加载和配置Spring上下文&#xff0c;特别是在测试场景中。 它允许开发者指定要加载的配置文件或配置类的位置&#xff0c;以便在运行时或测试时能够正确地构建和初始化Spring上下文。 基本用途和工…

【开源社区】Elasticsearch(ES)中空值字段 null_value 及通过exists查找非空文档

文章目录 0、声明1、问题描述2、问题剖析2.1 NULL或者空值类型有哪些2.2 案例讲解&#xff1a;尝试检索值为 null 的字段2.3 解决思路 3、使用 null_value 的诸多坑&#xff08;避免生产事故&#xff09;3.1 null_value 替换的是索引&#xff0c;并不会直接替换源数据3.2 不支持…

LVS(Linux Virtual Server)详解

LVS&#xff08;Linux Virtual Server&#xff09;是一个用于负载均衡的开源软件项目&#xff0c;旨在通过集群技术实现高性能、高可用的服务器系统。它运行在Linux操作系统上&#xff0c;并且可以利用内核级的资源来提高性能和稳定性。 思维导图 LVS的工作原理 LVS主要基于Ne…

IDEA 2022.1.4用前需知

目录 一、配置国内源 二、正确再次创建新项目方式 IDEA 2022.1.4下载地址 一、配置国内源 1、查看本地仓库地址 2、设置国内源-添加Setting.xml文件内容 3、修改目录&#xff08;考虑到当前硬盘空间大小&#xff0c;英文目录名&#xff09; 1&#xff09;创建你要移动过去…

xCat部署及分发操作系统

一、环境准备 此次安装部署均在VMware虚拟机上运行。系统采用通用稳定的centos7系统,移植到其他(linux)系统应该问题不大。软件服务器的VMware虚拟机的创建部分就跳过了. 1.1服务器的配置 IP主机名配置备注192.168.11.10master4C/8G/60GXcat/DNS/DHCP/NTP/TFTP192.168.11.11n…

【超音速专利 CN109636858A】锂电池涂布图像采集标定方法、系统、设备及存储介质

申请号CN201811276578.4公开号&#xff08;公开&#xff09;CN109636858A申请日2018.10.30申请人&#xff08;公开&#xff09;广州超音速自动化科技股份有限公司(超音速人工智能科技股份有限公司)发明人&#xff08;公开&#xff09;赵兵锁(张); 张俊峰(张); 梁土伟 相关术语…

读零信任网络:在不可信网络中构建安全系统14流量信任

1. 流量信任 1.1. 网络流的验证和授权是零信任网络至关重要的机制 1.2. 零信任并非完全偏离已知的安全机制&#xff0c;传统的网络过滤机制在零信任网络中仍然扮演着重要的角色 2. 加密和认证 2.1. 加密和认证通常是紧密相关的&#xff0c;尽管其目的截然不同 2.1.1. 加密提…

Spring Boot - 开启log-request-details详细记录调测Controller接口

文章目录 概述实现详细日志输出1. 调整日志级别2. 示例接口3. 启用请求详细信息日志 注意事项 概述 在Spring Boot项目中&#xff0c;调试Controller接口的请求和响应信息可以极大地帮助开发人员排查问题并确保应用程序的安全性和性能。 实现详细日志输出 1. 调整日志级别 …

在LabVIEW中高效读取大型CSV文件的方法

当尝试使用“读取分隔的电子表格VI”从大型CSV文件&#xff08;数百MB&#xff09;中读取数据时&#xff0c;可能会遇到内存已满错误。这是因为该VI会一次性读取整个文件并将其转换为数值数组&#xff0c;导致占用大量内存。 解决方案 可以使用“从文本文件VI读取”来部分读取…