Skip to content

Instantly share code, notes, and snippets.

@mturoci
mturoci / app.py
Created September 20, 2022 16:16
q.client.event = Event()
with concurrent.futures.ProcessPoolExecutor() as pool:
await q.exec(pool, blocking_function, q)
@mturoci
mturoci / app.py
Created September 20, 2022 16:15
q.client.event = Event()
with concurrent.futures.ProcessPoolExecutor() as pool:
await q.exec(pool, blocking_function, q)
@mturoci
mturoci / app.py
Created September 20, 2022 16:15
if q.args.cancel:
q.client.event.set()
@mturoci
mturoci / app.py
Created September 20, 2022 16:13
# This takes a lot of time (compute heavy).
async def blocking_function(q: Q):
count = 0
total = 20
while count < total:
# Check if cancelled.
if q.client.event.is_set():
await show_cancel(q)
return
# This blocks the main thread and prevents any other execution.
@mturoci
mturoci / app.py
Created September 20, 2022 16:13
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)
@mturoci
mturoci / app.py
Created September 20, 2022 16:10
# 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!',
@mturoci
mturoci / app.py
Created September 20, 2022 16:09
async def polling_function(q: Q):
count = 0
total = 20
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()
@mturoci
mturoci / app.py
Created September 20, 2022 16:08
import asyncio
import time
import concurrent.futures
from threading import Event
from h2o_wave import main, app, Q, ui
# This takes a lot of time (compute heavy).
def blocking_function(q: Q, loop: asyncio.AbstractEventLoop):
count = 0
@mturoci
mturoci / app.py
Created September 20, 2022 16:08
if q.args.cancel:
q.client.event.set()
@mturoci
mturoci / app.py
Created September 20, 2022 16:07
# Do not run like this - will block the whole thread - freeze the app.
# blocking_function(q, loop)
# Get the current event loop - will be used for
# running async functions within the blocking.
loop = asyncio.get_event_loop()
# Create an event to use for cancellation.
q.client.event = Event()
with concurrent.futures.ThreadPoolExecutor() as pool:
await q.exec(pool, blocking_function, q, loop)