找回密码
 会员注册
查看: 28|回复: 0

PythonPyWebIO初体验:用Python写网页

[复制链接]

7

主题

0

回帖

22

积分

新手上路

积分
22
发表于 2024-9-5 13:30:15 | 显示全部楼层 |阅读模式
目录前言1使用方法1.1安装Pywebio1.2输出内容1.3输入内容2示例程序2.1BMI计算器2.2Markdown编辑器2.3聊天室2.4五子棋前言前两天正在逛Github,偶然看到一个很有意思的项目:PyWebIo。这是一个Python第三方库,可以只用Python语言写出一个网页,而且支持Flask,Django,Tornado等web框架。甚至,它可以支持数据可视化图表的绘制,还提供了一行函数渲染Markdown文本。那么话不多说,正片开始——仓库地址:https://github.com/pywebio/PyWebIO1使用方法1.1安装Pywebio打开CMD,在里面输入以下代码:pipinstallpywebio1如果速度太慢,建议使用国内镜像:pipinstall-ihttps://pypi.tuna.tsinghua.edu.cn/simplepywebio11.2输出内容put_text()输出文字put_table()输出表格put_markdown()输出markdown内容put_file()输出文件下载链接put_image()输出图片put_button()输出按钮请看示例程序:frompywebio.outputimport*defmain():#文本输出put_text("Helloworld!")#表格输出put_table([['商品','价格'],['苹果','5.5'],['香蕉','7'],])#Markdown输出put_markdown('~~删除线~~')#文件输出put_file('hello_word.txt',b'helloword!')if__name__=='__main__':main()1234567891011121314151617181920211.3输入内容input()和python一样的函数欸frompywebio.inputimport*defmain():name=input("请输入你的名字:")if__name__=='__main__':main()12345672示例程序这些都是官方给出的实例,代码都不到100行!官方项目地址:https://pywebio-demos.pywebio.online/2.1BMI计算器frompywebio.inputimportinput,FLOATfrompywebio.outputimportput_textdefbmi():height=input("YourHeight(cm):",type=FLOAT)weight=input("YourWeight(kg):",type=FLOAT)BMI=weight/(height/100)**2top_status=[(14.9,'Severelyunderweight'),(18.4,'Underweight'),(22.9,'Normal'),(27.5,'Overweight'),(40.0,'Moderatelyobese'),(float('inf'),'Severelyobese')]fortop,statusintop_status:ifBMIMAX_MESSAGES_CNT:chat_msgs=chat_msgs[len(chat_msgs)//2:]last_idx=len(chat_msgs)asyncdefmain():"""PyWebIOchatroomYoucanchatwitheveryonecurrentlyonline."""globalchat_msgsput_markdown(t("##PyWebIOchatroom\nWelcometothechatroom,youcanchatwithallthepeoplecurrentlyonline.Youcanopenthispageinmultipletabsofyourbrowsertosimulateamulti-userenvironment.Thisapplicationuseslessthan90linesofcode,thesourcecodeis[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=awaitinput(t("Yournickname","请输入你的昵称"),required=True,validate=lambdan:t('Thisnameisalreadybeenused','昵称已被使用')ifninonline_usersorn=='📢'elseNone)online_users.add(nickname)chat_msgs.append(('📢','`%s`joinstheroom.%suserscurrentlyonline'%(nickname,len(online_users))))put_markdown('`📢`:`%s`jointheroom.%suserscurrentlyonline'%(nickname,len(online_users)),sanitize=True,scope='msg-box')@defer_calldefon_close()nline_users.remove(nickname)chat_msgs.append(('📢','`%s`leavestheroom.%suserscurrentlyonline'%(nickname,len(online_users))))refresh_task=run_async(refresh_msg(nickname))whileTrue:data=awaitinput_group(t('Sendmessage','发送消息'),[input(name='msg',help_text=t('MessagecontentsupportsinlineMarkdownsyntax','消息内容支持行内Markdown语法')),actions(name='cmd',buttons=[t('Send','发送'),t('MultilineInput','多行输入'),{'label':t('Exit','退出'),'type':'cancel'}])],validate=lambdad'msg','Messagecontentcannotbeempty')ifd['cmd']==t('Send','发送')andnotd['msg']elseNone)ifdataisNone:breakifdata['cmd']==t('MultilineInput','多行输入'):data['msg']='\n'+awaittextarea('Messagecontent',help_text=t('MessagecontentsupportsMarkdownsyntax','消息内容支持Markdown语法'))put_markdown('`%s`:%s'%(nickname,data['msg']),sanitize=True,scope='msg-box')chat_msgs.append((nickname,data['msg']))refresh_task.close()toast("Youhaveleftthechatroom")if__name__=='__main__':start_server(main,debug=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475762.4五子棋importtimefrompywebioimportsession,start_serverfrompywebio.outputimport*goboard_size=15#-1->none,0->black,1->whitegoboard=[[-1]*goboard_sizefor_inrange(goboard_size)]defwinner():#returnwinnerpiece,returnNoneifnowinnerforxinrange(2,goboard_size-2):foryinrange(2,goboard_size-2):#checkif(x,y)isthewincenterifgoboard[x][y]!=-1andany([all(goboard[x][y]==goboard[m][n]form,nin[(x-2,y),(x-1,y),(x+1,y),(x+2,y)]),all(goboard[x][y]==goboard[m][n]form,nin[(x,y-2),(x,y-1),(x,y+1),(x,y+2)]),all(goboard[x][y]==goboard[m][n]form,nin[(x-2,y-2),(x-1,y-1),(x+1,y+1),(x+2,y+2)]),all(goboard[x][y]==goboard[m][n]form,nin[(x-2,y+2),(x-1,y+1),(x+1,y-1),(x+2,y-2)]),]):return['⚫','⚪'][goboard[x][y]]session_id=0#autoincrementedidforeachsessioncurrent_turn=0#0forblack,1forwhiteplayer_count=[0,0]#countofplayerfortworolesdefmain():"""OnlineSharedGomokuGameAwebbasedGomoku(AKAGoBang,FiveinaRow)gamemadewithPyWebIOunder100linesofPythoncode."""globalsession_id,current_turn,goboardifwinner():#Thecurrentgameisover,resetgamegoboard=[[-1]*goboard_sizefor_inrange(goboard_size)]current_turn=0my_turn=session_id%2my_chess=['⚫','⚪'][my_turn]session_id+=1player_count[my_turn]+=1@session.defer_calldefplayer_exit():player_count[my_turn]-=1session.set_env(output_animation=False)put_html("""""")#Customstylestomaketheboardmorebeautifulput_markdown(f"""#OnlineSharedGomokuGameAllonlineplayersareassignedtotwogroups(blackandwhite)andsharethisgame.Youcanopenthispageinmultipletabsofyourbrowsertosimulatemultipleusers.Thisapplicationuseslessthan100linesofcode,thesourcecodeis[here](https://github.com/wang0618/PyWebIO/blob/dev/demos/gomoku_game.py)Currentlyonlineplayer:{player_count[0]}for⚫,{player_count[1]}for⚪.Yourroleis{my_chess}.""")defset_stone(pos):globalcurrent_turnifcurrent_turn!=my_turn:toast("It'snotyourturn!!",color='error')returnx,y=posgoboard[x][y]=my_turncurrent_turn=(current_turn+1)%2@use_scope('goboard',clear=True)defshow_goboard():table=[[put_buttons([dict(label='',value=(x,y),color='light')],onclick=set_stone)ifcell==-1else['⚫','⚪'][cell]fory,cellinenumerate(row)]forx,rowinenumerate(goboard)]put_table(table)show_goboard()whilenotwinner():withuse_scope('msg',clear=True):current_turn_copy=current_turnifcurrent_turn_copy==my_turn:put_text("It'syourturn!")else:put_row([put_text("Youropponent'sturn,waiting..."),put_loading().style('width:1.5em;height:1.5em')],size='auto1fr')whilecurrent_turn==current_turn_copyandnotsession.get_current_session().closed():#waitfornextmovetime.sleep(0.2)show_goboard()withuse_scope('msg',clear=True):put_text('Gameover.Thewinneris%s!\nRefreshpagetostartanewround.'%winner())if__name__=='__main__':start_server(main,debug=True,port=8080)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394稍微试了试这个第三方库,感觉功能十分的强大。不只是上面的项目,它还有不同风格,能绘制不同图表,集成web框架。有了这个库,我们就可以轻松地将Python程序展示在网页上,也就是实现使用Python开发前端!本文就到这里,如果喜欢的话别望点赞收藏!拜~
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2025-1-7 06:16 , Processed in 0.524987 second(s), 26 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表