Skip to content

Instantly share code, notes, and snippets.

@drgarcia1986
Created August 15, 2015 02:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drgarcia1986/050df09802e4dd25d1a0 to your computer and use it in GitHub Desktop.
Save drgarcia1986/050df09802e4dd25d1a0 to your computer and use it in GitHub Desktop.
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
Copy link

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