Last active
May 25, 2022 11:55
-
-
Save Integralist/d0732065f2d230d5e715bc186546bf90 to your computer and use it in GitHub Desktop.
[Wait for multiple Python futures to finish using asyncio.wait()] #asyncio #wait #concurrency #multiple #requests #httpclient
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import asyncio | |
import requests | |
domain = 'http://integralist.co.uk' | |
a = '{}/foo?run={}'.format(domain, time.time()) | |
b = '{}/bar?run={}'.format(domain, time.time()) | |
async def get(url): | |
print('start: ', url) | |
r = requests.get(url) | |
print('done: ', url) | |
return await asyncio.sleep(0, result=r) | |
async def get_pages(x, y): | |
tasks = [get(x), get(y)] | |
done, pending = await asyncio.wait(tasks, return_when=FIRST_COMPLETED) # also FIRST_EXCEPTION and ALL_COMPLETED (default) | |
print('>> done: ', done) | |
print('>> pending: ', pending) # will be empty if using default return_when setting | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(get_pages(a, b)) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FIRST_COMPLETED
should beasyncio.FIRST_COMPLETED