亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

PyWebIO使用初體驗(yàn)之用Python寫網(wǎng)頁(yè)

 更新時(shí)間:2024年12月18日 09:06:17   作者:黑洞Qix  
這篇文章主要介紹了PyWebIO使用初體驗(yàn)之用Python寫網(wǎng)頁(yè)的相關(guān)資料,PyWebIo是一個(gè)功能強(qiáng)大的Python第三方庫(kù),可以使用Python語(yǔ)言輕松創(chuàng)建網(wǎng)頁(yè),并且支持Flask、Django等Web框架,需要的朋友可以參考下

前言

前兩天正在逛 Github,偶然看到一個(gè)很有意思的項(xiàng)目:PyWebIo。

這是一個(gè) Python 第三方庫(kù),可以只用 Python 語(yǔ)言寫出一個(gè)網(wǎng)頁(yè),而且支持 Flask,Django,Tornado 等 web 框架。

甚至,它可以支持?jǐn)?shù)據(jù)可視化圖表的繪制,還提供了一行函數(shù)渲染 Markdown 文本。

那么話不多說(shuō),正片開(kāi)始——

倉(cāng)庫(kù)地址:https://github.com/pywebio/PyWebIO

1 使用方法

1.1 安裝 Pywebio

打開(kāi) CMD,在里面輸入以下代碼:

pip install pywebio

如果速度太慢,建議使用國(guó)內(nèi)鏡像:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pywebio

1.2 輸出內(nèi)容

  • put_text() 輸出文字
  • put_table() 輸出表格
  • put_markdown() 輸出 markdown 內(nèi)容
  • put_file() 輸出文件下載鏈接
  • put_image() 輸出圖片
  • put_button() 輸出按鈕

請(qǐng)看示例程序:

from pywebio.output import *

def main():
    # 文本輸出
    put_text("Hello world!")
    
    # 表格輸出
    put_table([
        ['商品', '價(jià)格'],
        ['蘋果', '5.5'],
        ['香蕉', '7'],
    ])
  
    # Markdown輸出
    put_markdown('~~刪除線~~')
  
    # 文件輸出
    put_file('hello_word.txt', b'hello word!')

if __name__ == '__main__':
    main()

1.3 輸入內(nèi)容

  • input() 和 python 一樣的函數(shù)欸
from pywebio.input import *

def main():
    name = input("請(qǐng)輸入你的名字:")

if __name__ == '__main__':
    main()

2 示例程序

這些都是官方給出的實(shí)例,代碼都不到 100 行!

官方項(xiàng)目地址:https://pywebio-demos.pywebio.online/

2.1 BMI 計(jì)算器

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歡迎來(lái)到聊天室,你可以和當(dāng)前所有在線的人聊天。你可以在瀏覽器的多個(gè)標(biāo)簽頁(yè)中打開(kāi)本頁(yè)面來(lái)測(cè)試聊天效果。本應(yīng)用使用不到90行代碼實(shí)現(xiàn),源代碼[鏈接](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", "請(qǐng)輸入你的昵稱"), 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', '發(fā)送消息'), [
            input(name='msg', help_text=t('Message content supports inline Markdown syntax', '消息內(nèi)容支持行內(nèi)Markdown語(yǔ)法')),
            actions(name='cmd', buttons=[t('Send', '發(fā)送'), t('Multiline Input', '多行輸入'), {'label': t('Exit', '退出'), 'type': 'cancel'}])
        ], validate=lambda d: ('msg', 'Message content cannot be empty') if d['cmd'] == t('Send', '發(fā)送') 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', '消息內(nèi)容支持Markdown語(yǔ)法'))
        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)

稍微試了試這個(gè)第三方庫(kù),感覺(jué)功能十分的強(qiáng)大。

不只是上面的項(xiàng)目,它還有不同風(fēng)格,能繪制不同圖表,集成web框架。

有了這個(gè)庫(kù),我們就可以輕松地將 Python 程序展示在網(wǎng)頁(yè)上,也就是實(shí)現(xiàn)使用 Python 開(kāi)發(fā)前端!

總結(jié)

到此這篇關(guān)于PyWebIO使用初體驗(yàn)之用Python寫網(wǎng)頁(yè)的文章就介紹到這了,更多相關(guān)PyWebIO Python寫網(wǎng)頁(yè)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python實(shí)現(xiàn)雙向鏈表

    Python實(shí)現(xiàn)雙向鏈表

    這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)雙向鏈表,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • 在Python中操作字典之update()方法的使用

    在Python中操作字典之update()方法的使用

    這篇文章主要介紹了在Python中操作字典之update()方法的使用,是Python入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-05-05
  • Python實(shí)現(xiàn)圖書(shū)借閱管理系統(tǒng)

    Python實(shí)現(xiàn)圖書(shū)借閱管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)圖書(shū)借閱管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Python海龜繪圖詳解

    Python海龜繪圖詳解

    python2.6版本中后引入的一個(gè)簡(jiǎn)單的繪圖工具,叫做海龜繪圖(Turtle Graphics),出現(xiàn)在1966年的Logo計(jì)算機(jī)語(yǔ)言。海龜繪圖(turtle庫(kù))是python的內(nèi)部模塊,使用前導(dǎo)入即可。本文就帶大家深入了解一下海龜繪圖,快來(lái)跟隨小編一起學(xué)習(xí)吧
    2021-12-12
  • Python繪制七段數(shù)碼管字母

    Python繪制七段數(shù)碼管字母

    在現(xiàn)代電子顯示技術(shù)中,七段數(shù)碼管是一種廣泛應(yīng)用的顯示器件,常用于顯示數(shù)字、字母和一些特殊符號(hào),本文將詳細(xì)介紹如何使用Python繪制七段數(shù)碼管顯示字母的過(guò)程,需要的可以參考下
    2024-12-12
  • django 解決model中類寫不到數(shù)據(jù)庫(kù)中,數(shù)據(jù)庫(kù)無(wú)此字段的問(wèn)題

    django 解決model中類寫不到數(shù)據(jù)庫(kù)中,數(shù)據(jù)庫(kù)無(wú)此字段的問(wèn)題

    這篇文章主要介紹了django 解決model中類寫不到數(shù)據(jù)庫(kù)中,數(shù)據(jù)庫(kù)無(wú)此字段的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨想過(guò)來(lái)看看吧
    2020-05-05
  • 對(duì)Python _取log的幾種方式小結(jié)

    對(duì)Python _取log的幾種方式小結(jié)

    今天小編就為大家分享一篇對(duì)Python _取log的幾種方式小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-07-07
  • Python字典取值全攻略之高效、簡(jiǎn)潔地獲取字典值的多種技巧

    Python字典取值全攻略之高效、簡(jiǎn)潔地獲取字典值的多種技巧

    這篇文章主要給大家介紹了關(guān)于Python字典取值全攻略之高效、簡(jiǎn)潔地獲取字典值的多種技巧,dictionary(字典)是除列表以外Python之中最靈活的數(shù)據(jù)類型,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-12-12
  • python讀寫刪除復(fù)制文件操作方法詳細(xì)實(shí)例總結(jié)

    python讀寫刪除復(fù)制文件操作方法詳細(xì)實(shí)例總結(jié)

    這篇文章主要介紹了python讀寫刪除復(fù)制文件操作方法詳細(xì)實(shí)例總結(jié),需要的朋友可以參考下
    2021-04-04
  • 如何利用Python處理excel表格中的數(shù)據(jù)

    如何利用Python處理excel表格中的數(shù)據(jù)

    Excel做為職場(chǎng)人最常用的辦公軟件,具有方便、快速、批量處理數(shù)據(jù)的特點(diǎn),下面這篇文章主要給大家介紹了關(guān)于如何利用Python處理excel表格中數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下
    2022-03-03

最新評(píng)論