Python 3.5 增長了對async def
and await
的支持,一樣的異步代碼看起來乾淨了不少,也更易讀。python
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()
原文連接:http://leeeric.com/post/asynchronous-http-requests-in-Python-3-5/git