首先我們要先理解異步請求,以下是示例代碼
import asyncio
import time
import aiohttp
#定義第1個協程,協程就是將要具體完成的任務,該任務耗時3秒,完成后顯示任務完成
async def to_do_something(i):
print('第{}個任務:任務啟動...'.format(i))
#遇到耗時的操作,await就會使任務掛起,繼續去完成下一個任務
await asyncio.sleep(i)
print('第{}個任務:任務完成!'.format(i))
#定義第2個協程,用於通知任務進行狀態
async def mission_running():
print('任務正在執行...')
start = time.time()
#創建一個循環
loop = asyncio.get_event_loop()
#創建一個任務盒子tasks,包含了3個需要完成的任務 , 創建task有兩種方法 第1種: loop.create_task(coroutine) 第二種: asyncio.ensure_future()
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())]
#tasks接入loop中開始運行鄭州做人流多少錢 http://www.120zzzzyy.com/
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)