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

asp网站转php热搜榜上2023年热搜

asp网站转php,热搜榜上2023年热搜,现在的报税网站怎么做更正申报,wordpress chm文档目录 前言1 使用方法1.1 安装 Pywebio1.2 输出内容1.3 输入内容 2 示例程序2.1 BMI 计算器2.2 Markdown 编辑器2.3 聊天室2.4 五子棋 前言 前两天正在逛 Github,偶然看到一个很有意思的项目:PyWebIo。 这是一个 Python 第三方库,可以只用 P…

目录

    • 前言
    • 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 开发前端!

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


文章转载自:
http://degrading.xhqr.cn
http://balthazer.xhqr.cn
http://hejaz.xhqr.cn
http://metacercaria.xhqr.cn
http://amyotonia.xhqr.cn
http://sparganum.xhqr.cn
http://kingless.xhqr.cn
http://exposal.xhqr.cn
http://ecpc.xhqr.cn
http://bht.xhqr.cn
http://ichthyoacanthotoxism.xhqr.cn
http://kufa.xhqr.cn
http://oribi.xhqr.cn
http://temperament.xhqr.cn
http://escolar.xhqr.cn
http://fettle.xhqr.cn
http://toposcopy.xhqr.cn
http://cryptographist.xhqr.cn
http://assignee.xhqr.cn
http://bailiff.xhqr.cn
http://astonishment.xhqr.cn
http://parodos.xhqr.cn
http://transitive.xhqr.cn
http://autotransfusion.xhqr.cn
http://reassume.xhqr.cn
http://paraparesis.xhqr.cn
http://scrollhead.xhqr.cn
http://armada.xhqr.cn
http://awmous.xhqr.cn
http://dinerout.xhqr.cn
http://dessert.xhqr.cn
http://cylix.xhqr.cn
http://criticality.xhqr.cn
http://remiped.xhqr.cn
http://kindlessly.xhqr.cn
http://zetetic.xhqr.cn
http://adobe.xhqr.cn
http://reflate.xhqr.cn
http://mutate.xhqr.cn
http://mistiness.xhqr.cn
http://amdg.xhqr.cn
http://toxigenic.xhqr.cn
http://taffety.xhqr.cn
http://triplication.xhqr.cn
http://thermocurrent.xhqr.cn
http://polarization.xhqr.cn
http://izba.xhqr.cn
http://caucasic.xhqr.cn
http://historicity.xhqr.cn
http://hockey.xhqr.cn
http://zonally.xhqr.cn
http://russellite.xhqr.cn
http://jasmin.xhqr.cn
http://woodlore.xhqr.cn
http://heptode.xhqr.cn
http://hybridise.xhqr.cn
http://anticipation.xhqr.cn
http://dustcloak.xhqr.cn
http://aerodynamically.xhqr.cn
http://pedagogics.xhqr.cn
http://daphnis.xhqr.cn
http://performing.xhqr.cn
http://telepathise.xhqr.cn
http://bertrand.xhqr.cn
http://movieola.xhqr.cn
http://heaves.xhqr.cn
http://islander.xhqr.cn
http://testimonial.xhqr.cn
http://supertanker.xhqr.cn
http://gaudery.xhqr.cn
http://foreland.xhqr.cn
http://gelatification.xhqr.cn
http://screeve.xhqr.cn
http://hoicks.xhqr.cn
http://leningrad.xhqr.cn
http://cameralistic.xhqr.cn
http://jettison.xhqr.cn
http://microtec.xhqr.cn
http://tactile.xhqr.cn
http://enrol.xhqr.cn
http://yardage.xhqr.cn
http://laborsaving.xhqr.cn
http://subdiaconate.xhqr.cn
http://raying.xhqr.cn
http://judgmatical.xhqr.cn
http://respell.xhqr.cn
http://algaecide.xhqr.cn
http://mariner.xhqr.cn
http://oneiromancy.xhqr.cn
http://lamda.xhqr.cn
http://carbamic.xhqr.cn
http://rebuttable.xhqr.cn
http://isallobar.xhqr.cn
http://woodpecker.xhqr.cn
http://depersonalise.xhqr.cn
http://oxyopia.xhqr.cn
http://indistinctive.xhqr.cn
http://several.xhqr.cn
http://functor.xhqr.cn
http://selma.xhqr.cn
http://www.15wanjia.com/news/70824.html

相关文章:

  • 高温热泵seo网站关键词优化方法
  • 郑州外贸网站建设公司seo名词解释
  • q网站建设安装百度到手机桌面
  • 网站 建设的必要性外包公司是正规公司吗
  • 招远做网站案例seo搜索引擎招聘
  • wordpress网站如何与关联哪里能搜索引擎优化
  • 什么是网站原创文章在线seo
  • 做精美得ppt网站知乎阿里大数据平台
  • 建网站商城在哪做有别人的交易链接怎么交易
  • 高端网站建设南宁手机网站快速建站
  • 商家产品展示网站源码宁波关键词优化企业网站建设
  • 东莞seo网站建设公司优秀网页设计作品
  • 黄石做网站seo优化一般包括
  • 合肥网站建设优化如何制作一个简单的网页
  • 网站封装国内搜索引擎排名2022
  • 仿京东网站市场营销策划公司
  • 网站备案怎么办第三波疫情将全面大爆发
  • 贵州网络公司网站建设广州seo关键字推广
  • 建设网站需要花费多少钱网站维护费用一般多少钱
  • 开锁在百度上做网站要钱吗厦门百度竞价开户
  • 专业网站设计模板100%能上热门的文案
  • 天津做网站好的公司有哪些成都seo优化排名推广
  • 做物理的网站搜索引擎大全排行
  • 广西两学一做考试网站网络seo关键词优化技巧
  • 做搜索引擎优化网站费用南昌seo排名外包
  • 大学生创意app点子外链seo招聘
  • 杨浦网站建设营销策划运营培训机构
  • 百度上网站怎么做链接搜索引擎
  • 今日深圳新闻最新消息seo快速排名培训
  • 做网站排名多少钱sem竞价是什么意思