Skip to content

Instantly share code, notes, and snippets.

@mturoci
Created September 20, 2022 16:17
Show Gist options
  • Save mturoci/7fd02e5ae198214d4b2e30e25892436c to your computer and use it in GitHub Desktop.
Save mturoci/7fd02e5ae198214d4b2e30e25892436c to your computer and use it in GitHub Desktop.
async def download_file(q: Q):
# Create a tmp file to store the downloaded contents.
with open('my_download', 'wb') as tmp_file:
# Random URL to download a 100MB file.
url = 'https://speed.hetzner.de/100MB.bin'
# Get async HTTP client.
async with httpx.AsyncClient() as client:
# Stream the response to get periodic download updates.
async with client.stream('GET', url) as response:
total = int(response.headers['Content-Length'])
# Go over received chunks and write them to the file as needed.
async for chunk in response.aiter_bytes():
# Check if cancelled.
if q.client.event.is_set():
q.page['meta'].dialog.items[0].progress.caption = 'Cancelled'
return
# Write received bytes to a tmp file on disk.
tmp_file.write(chunk)
# Update the Wave UI.
progress_val = response.num_bytes_downloaded / total
q.page['meta'].dialog.items[0].progress.value = progress_val
await q.page.save()
await show_notification(q)
async def show_notification(q: Q):
q.page['meta'].dialog = None
q.page['meta'].notification_bar = ui.notification_bar(
name='success_notification',
text='Job done!',
type='success',
events=['dismissed']
)
await q.page.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment