import asyncio
import time
import aiohttp
urls = [
'http://127.0.0.1:5000/bobo',
'http://127.0.0.1:5000/haha',
'http://127.0.0.1:5000/guagua'
]
async def get_page(url):
print('正在请求:',url)
async with aiohttp.ClientSession() as session:
async with await session.get(url) as response:
page_text = await response.text()
print('请求完毕:',page_text)
tasks = []
stark_time = time.time()
for url in urls:
c=get_page(url)
task = asyncio.ensure_future(c)
tasks.append(task)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
end_time = time.time()
print('总耗时:',end_time-stark_time)
打印结果:
正在请求: http://127.0.0.1:5000/bobo
正在请求: http://127.0.0.1:5000/haha
正在请求: http://127.0.0.1:5000/guagua
请求完毕: ok,guagua
请求完毕: ok,bobo
请求完毕: ok,haha
总耗时: 3.005218267440796
Process finished with exit code 0