aluriak
aluriak

Reputation: 5847

How to show page before total computation of widgets?

Context: i have a web page with many buttons, each being a link to another website. As these websites are not always up, i make a request to each of these website, then add a badge on associated button, 'ok' in green if website was reached, else 'ko' in red.

The problem: the page takes long to show, because nicegui is waiting for the requests to other website to finish, to render the badges, to render the page.

I would like the page to render, with no or 'trying to reach...' badges first, then populating/changing the badges when the requests finishes, letting the user use my website even if requets didn't terminate.

What i tried :

Here is a code where i tried using asyncio tasks, without success (page is still waiting for sleeps to finish) :

import time
import asyncio
from nicegui import ui, run


SERVICES = {
    'A': 'https://example.net',
    'B': 'https://example.net',
    'C': 'https://example.net',
    'D': 'https://example.net',
}


def render_buttons() -> dict[str, ui.button]:
    buttons = []
    for service, url in SERVICES.items():
        with ui.link(target=url):
            buttons.append(ui.button(service))
    return buttons

async def add_badge(button: ui.button):
    with button:
        print('requesting…')
        time.sleep(1.0)  # simulate the http request
        ui.badge('up', color='green').props('floating')

@ui.page('/')
async def the_page():
    buttons = render_buttons()
    tasks = []
    for button in buttons:
        tasks.append(asyncio.create_task(add_badge(button)))
    for task in tasks:
        await task


ui.run()

Can you help me ?

Upvotes: 0

Views: 42

Answers (0)

Related Questions