Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python asyncio.wait example with identified futures.
import asyncio
import aiohttp
URL_LIST = [
'http://google.com',
'http://abc.xyz',
'http://github.com',
'https://www.python.org/'
]
@asyncio.coroutine
def fetch_url(url):
response = yield from aiohttp.request('GET', url)
return (yield from response.text())
if __name__ == '__main__':
loop = asyncio.get_event_loop()
urls = {
asyncio.async(fetch_url(url)): url
for url in URL_LIST
}
responses, _ = loop.run_until_complete(asyncio.wait(urls))
for response in responses:
url = urls[response]
print('{}: {}'.format(url, len(response.result())))
loop.close()
@pathammer

This comment has been minimized.

Copy link

@pathammer pathammer commented Nov 30, 2016

Thanks for this great sample!

Just a note, asyncio.async has been deprecated since 3.4.4, replaced with asyncio.ensure_future()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment