Created
August 15, 2015 02:57
-
-
Save drgarcia1986/050df09802e4dd25d1a0 to your computer and use it in GitHub Desktop.
Python asyncio.wait example with identified futures.
This file contains 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 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this great sample!
Just a note, asyncio.async has been deprecated since 3.4.4, replaced with asyncio.ensure_future()