1、asyncio 下面經過舉例來對比同步代碼和異步代碼編寫方面的差別,其次看下二者性能上的差距,咱們使用sleep(1)模擬耗時1秒的io操做。html
同步代碼:session
import time def hello(): time.sleep(1) def run(): for i in range(5): hello() print('Hello World:%s' % time.time()) # 任何偉大的代碼都是從Hello World 開始的! if name == 'main': run()併發
輸出:(間隔差很少是1s)app
Hello World:1527595175.4728756 Hello World:1527595176.473001 Hello World:1527595177.473494 Hello World:1527595178.4739306 Hello World:1527595179.474482異步
異步代碼:async
import time import asyncio # 定義異步函數 async def hello(): asyncio.sleep(1) print('Hello World:%s' % time.time()) def run(): for i in range(5): loop.run_until_complete(hello())函數
loop = asyncio.get_event_loop() if name =='main': run()oop
輸出:post
Hello World:1527595104.8338501 Hello World:1527595104.8338501 Hello World:1527595104.8338501 Hello World:1527595104.8338501 Hello World:1527595104.8338501性能
async def 用來定義異步函數,其內部有異步操做。每一個線程有一個事件循環,主線程調用asyncio.get_event_loop()時會建立事件循環,你須要把異步的任務丟給這個循環的run_until_complete()方法,事件循環會安排協同程序的執行。
2、aiohttp 若是須要併發http請求怎麼辦呢,一般是用requests,但requests是同步的庫,若是想異步的話須要引入aiohttp。這裏引入一個類,from aiohttp import ClientSession,首先要創建一個session對象,而後用session對象去打開網頁。session能夠進行多項操做,好比post, get, put, head等。
基本用法:
async with ClientSession() as session: async with session.get(url) as response:
aiohttp異步實現的例子:
import asyncio from aiohttp import ClientSession
tasks = [] url = "https://www.baidu.com/{}" async def hello(url): async with ClientSession() as session: async with session.get(url) as response: response = await response.read() print(response) if name == 'main': loop = asyncio.get_event_loop() loop.run_until_complete(hello(url))
首先async def 關鍵字定義了這是個異步函數,await 關鍵字加在須要等待的操做前面,response.read()等待request響應,是個耗IO操做。而後使用ClientSession類發起http請求。
多連接異步訪問
若是咱們須要請求多個URL該怎麼辦呢,同步的作法訪問多個URL只須要加個for循環就能夠了。但異步的實現方式並沒那麼容易,在以前的基礎上須要將hello()包裝在asyncio的Future對象中,而後將Future對象列表做爲任務傳遞給事件循環。
import time import asyncio from aiohttp import ClientSession
tasks = [] url = "https://www.baidu.com/{}" async def hello(url): async with ClientSession() as session: async with session.get(url) as response: response = await response.read() # print(response) print('Hello World:%s' % time.time()) def run(): for i in range(5): task = asyncio.ensure_future(hello(url.format(i))) tasks.append(task) if name == 'main': loop = asyncio.get_event_loop() run() loop.run_until_complete(asyncio.wait(tasks))
輸出:
Hello World:1527754874.8915546 Hello World:1527754874.899039 Hello World:1527754874.90004 Hello World:1527754874.9095392 Hello World:1527754874.9190395
收集http響應
好了,上面介紹了訪問不一樣連接的異步實現方式,可是咱們只是發出了請求,若是要把響應一一收集到一個列表中,最後保存到本地或者打印出來要怎麼實現呢,可經過asyncio.gather(*tasks)將響應所有收集起來,具體經過下面實例來演示。
import time import asyncio from aiohttp import ClientSession
tasks = [] url = "https://www.baidu.com/{}" async def hello(url): async with ClientSession() as session: async with session.get(url) as response: # print(response) print('Hello World:%s' % time.time()) return await response.read() def run(): for i in range(5): task = asyncio.ensure_future(hello(url.format(i))) tasks.append(task) result = loop.run_until_complete(asyncio.gather(*tasks)) print(result) if name == 'main': loop = asyncio.get_event_loop() run()
輸出:
Hello World:1527765369.0785167 Hello World:1527765369.0845182 Hello World:1527765369.0910277 Hello World:1527765369.0920424 Hello World:1527765369.097017 [b'<!DOCTYPE html>\r\n<!--STATUS OK-->\r\n<html>\r\n<head>\r\n......
異常解決
假如你的併發達到1000個,程序會報錯:ValueError: too many file descriptors in select()。這個報錯的緣由是由於 Python 調取的 select 對打開的文件字符有最大長度限制。這裏咱們有兩種方法解決這個問題:1.咱們能夠須要限制併發數量。一次不要塞那麼多任務,或者限制最大併發數量。2.咱們能夠使用回調的方式。這裏我的推薦限制併發數的方法,設置併發數爲500或者600,處理速度更快。