纯Python的Web UI

只需要懂Python就可以了,不再需要学习 JavaScript HTML CSS
NiceGUI

NiceGUI httpx coroutine button click

import asyncio
import httpx
from nicegui import ui


async def add(url):
    print('----')
    l = ui.label('This should be visible')


    async with httpx.AsyncClient() as client:
        r = await client.get(url)
        res = r.json()
        l.text = res['ip']


ip_url = 'https://api.seeip.org/jsonip'
#ip_url = 'https://api.ipify.org/?format=json'

ui.button('Add label', on_click= lambda:add(ip_url))

ui.run(reload=False,  host="::", port=5678, favicon='🚀', title='httpx协程') 

报错

 RuntimeWarning: coroutine 'add' was never awaited
  self.on('click', lambda _: handle_event(on_click, ClickEventArguments(sender=self, client=self.client)))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

修改成不带参数的

import asyncio
import httpx
from nicegui import ui



#ip_url = 'https://api.seeip.org/jsonip'
ip_url = 'https://api.bigdatacloud.net/data/client-ip'

async def add():
    print('----')
    l = ui.label('Waiting...')


    async with httpx.AsyncClient() as client:
        r = await client.get(ip_url)
        res = r.json()
        l.text = res['ipString']



ui.button('Get IP', on_click=add)

ui.run(reload=False,  host="::", port=5678, favicon='🚀', title='httpx协程') 

真有传递参数,还是有办法的

How to pass an argument to an async function with a ui.button

import asyncio
import httpx
from nicegui import ui
from functools import partial


ip_url = 'https://api.seeip.org/jsonip'
#ip_url = 'https://ipv6.jsonip.com/'
#  https://ipv4.jsonip.com/
#  http://no-tls.jsonip.com/

async def add(url):
    print('----')
    l = ui.label('Waiting...')

    async with httpx.AsyncClient() as client:
        r = await client.get(url)
        res = r.json()
        l.text = res['ip']

ui.button('Get IP', on_click=partial(add, ip_url))

ui.run(reload=False,  host="::", port=5678, favicon='🚀', title='httpx协程') 

就是用 functools 的 partial

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注