Skip to content

Instantly share code, notes, and snippets.

@mturoci
Created September 20, 2022 16:13
Show Gist options
  • Save mturoci/053b5df1002b434f4d1acdf24122c1a5 to your computer and use it in GitHub Desktop.
Save mturoci/053b5df1002b434f4d1acdf24122c1a5 to your computer and use it in GitHub Desktop.
import asyncio
from h2o_wave import main, app, Q, ui
async def polling_function(q: Q):
count = 0
total = 10
while count < total:
# You would make an async HTTP call here in real-world to get the fresh data.
await q.sleep(1)
count +=1
q.page['meta'].dialog.items[0].progress.value = count / total
await q.page.save()
@app('/')
async def serve(q: Q):
# Unimportat, draw initial UI.
if not q.client.initialized:
q.page['meta'] = ui.meta_card(box='')
q.page['form'] = ui.form_card(box='1 1 1 1', items=[
ui.button(name='start_job', label='Start job'),
])
q.client.initialized = True
# Handle start job button click.
if q.args.start_job:
q.page['meta'].dialog = ui.dialog(title='Blocking job', blocking=True, items=[
ui.progress(label='Progress', value=0),
ui.button(name='cancel', label='Cancel'),
])
# Start the polling, wrap in future so that we can cancel it later.
q.client.future = asyncio.ensure_future(polling_function(q))
# Future cancellation raises an error - use trycatch.
try:
# Wait until polling finished.
await q.client.future
q.page['meta'].dialog = None
q.page['meta'].notification_bar = ui.notification_bar(
name='success_notification',
text='Job done!',
type='success',
events=['dismissed']
)
# Handle cancellation.
except asyncio.CancelledError:
q.page['meta'].dialog.items[0].progress.caption = 'Cancelled'
if q.args.cancel:
q.client.future.cancel()
# Unimportant, just handle notification dismissal.
if q.events.success_notification and q.events.success_notification.dismissed:
q.page['meta'].notification_bar = None
await q.page.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment