原因:多链接异步访问
# coding=utf-8
import time
import asyncio
from aiohttp import ClientSession
URL = 'http://httpbin.org/get?a={}'
async def hello (num):
async with ClientSession() as session:
async with session.get(URL.format(num)) as response:
data = await response.json()
print(f"fetch({num}) = {data['args']['a']}")
async def main (loop):
now = time.time()
tasks = []
for num in range(10):
task = asyncio.ensure_future(hello(num))
tasks.append(task)
await asyncio.wait(tasks)
print("总用时", time.time() - now)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
# ---------------------------------------------
try:
loop.run_until_complete(main(loop))
finally:
loop.close()
输出:
fetch(3) = 3
fetch(0) = 0
fetch(7) = 7
fetch(4) = 4
fetch(1) = 1
fetch(5) = 5
fetch(8) = 8
fetch(9) = 9
fetch(6) = 6
fetch(2) = 2
总用时 3.5336081981658936