Asynchronous HTTP requests in Python 3.5

Just a snippet with aiohttp.

import aiohttp
import asyncio

async def get_status(url, id):
    r = await aiohttp.get(url)
    print(r.status, id)
    r.close()


tasks = []
for i in range(100):
    tasks.append(asyncio.ensure_future(get_status('https://api.github.com/events', id=i)))


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

In Python 3.5, with the help of new syntaxes such as async def and await, the code which achieves asynchronous http requests can be cleaner. There's no co-routine decorator and no yield from in the code. The new syntaxes are also pretty explicit.

comments powered by Disqus