首先我们要先理解异步请求,以下是示例代码
import asyncio
import time
import aiohttp
async def to_do_something(i):
print('第{}个任务:任务启动...'.format(i))
await asyncio.sleep(i)
print('第{}个任务:任务完成!'.format(i))
async def mission_running():
print('任务正在执行...')
start = time.time()
loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(to_do_something(5)),
asyncio.ensure_future(to_do_something(2)),
asyncio.ensure_future(to_do_something(8)),
asyncio.ensure_future(mission_running())]
loop.run_until_complete(asyncio.wait(tasks))
end = time.time()
print(end-start)
并发请求100次百度首页只需1秒钟
import aiohttp
import aiohttp, asyncio, time
async def get(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
print(await response)
async def request():
url = 'http://www.baidu.com'
resulit = await get(url)
_now = lambda : time.time()
start = _now()
tasks = [asyncio.ensure_future(request()) for _ in range(100)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
print(_now()-start)