強化版的 requests,這個庫真牛 x

來源:Python 編程時光

最近公司 Python 後端項目進行重構,整個後端邏輯基本都變更爲採用 "異步" 協程的方式實現。看着滿屏幕經過 async await(協程在 Python 中的實現)修飾的代碼,我頓時感到一臉懵逼,不知所措。

雖然之前有了解過 "協程" 是什麼東西,但並沒有深入探索,於是正好藉着這次機會可以好好學習一下。

 什麼是協程?

簡單來說,協程是一種基於線程之上,但又比線程更加輕量級的存在。對於系統內核來說,協程具有不可見的特性,所以這種由 程序員自己寫程序來管理的輕量級線程又常被稱作 " 用戶空間線程 "。

 協程比多線程好在哪呢?

  1. 線程的控制權在操作系統手中,而 協程的控制權完全掌握在用戶自己手中,因此利用協程可以減少程序運行時的上下文切換,有效提高程序運行效率。

  2. 建立線程時,系統默認分配給線程的 棧 大小是 1 M,而協程更輕量,接近 1 K 。因此可以在相同的內存中開啓更多的協程。

  3. 由於協程的本質不是多線程而是單線程,所以不需要多線程的鎖機制。因爲只有一個線程,也不存在同時寫變量而引起的衝突。在協程中控制共享資源不需要加鎖,只需要判斷狀態即可。所以協程的執行效率比多線程高很多,同時也有效避免了多線程中的競爭關係。

 協程的適用 & 不適用場景

適用場景:協程適用於被阻塞的,且需要大量併發的場景。

不適用場景:協程不適用於存在大量計算的場景(因爲協程的本質是單線程來回切換),如果遇到這種情況,還是應該使用其他手段去解決。

 初探異步 http 框架 httpx

至此我們對 "協程" 應該有了個大概的瞭解,但故事說到這裏,相信有朋友還是滿臉疑問:"協程" 對於接口測試有什麼幫助呢?不要着急,答案就在下面。

相信用過 Python 做接口測試的朋友都對 requests 庫不陌生。requests 中實現的 http 請求是同步請求,但其實基於 http 請求 IO 阻塞的特性,非常適合用協程來實現 "異步" http 請求從而提升測試效率。

相信早就有人注意到了這點,於是在 Github 經過了一番探索後,果不其然,最終尋找到了支持協程 "異步" 調用 http 的開源庫: httpx

 什麼是 httpx

httpx 是一個幾乎繼承了所有 requests 的特性並且支持 "異步" http 請求的開源庫。簡單來說,可以認爲 httpx 是強化版 requests。

下面大家可以跟着我一起見識一下 httpx 的強大

 安裝

httpx 的安裝非常簡單,在 Python 3.6 以上的環境執行

pip install httpx

 最佳實踐

俗話說得好,效率決定成敗。我分別使用了 httpx 異步 和 同步 的方式對批量 http 請求進行了耗時比較,來一起看看結果吧~

首先來看看同步 http 請求的耗時表現:

import asyncio
import httpx
import threading
import time

def sync_main(url, sign):
    response = httpx.get(url).status_code
    print(f'sync_main: {threading.current_thread()}: {sign}2 + 1{response}')

sync_start = time.time()
[sync_main(url='http://www.baidu.com'sign=i) for i in range(200)]
sync_end = time.time()
print(sync_end - sync_start)

代碼比較簡單,可以看到在 sync_main 中則實現了同步 http 訪問百度 200 次。

運行後輸出如下(截取了部分關鍵輸出…):

sync_main: <_MainThread(MainThread, started 4471512512)>: 192: 200
sync_main: <_MainThread(MainThread, started 4471512512)>: 193: 200
sync_main: <_MainThread(MainThread, started 4471512512)>: 194: 200
sync_main: <_MainThread(MainThread, started 4471512512)>: 195: 200
sync_main: <_MainThread(MainThread, started 4471512512)>: 196: 200
sync_main: <_MainThread(MainThread, started 4471512512)>: 197: 200
sync_main: <_MainThread(MainThread, started 4471512512)>: 198: 200
sync_main: <_MainThread(MainThread, started 4471512512)>: 199: 200
16.56578803062439

可以看到在上面的輸出中, 主線程沒有進行切換(因爲本來就是單線程啊喂!)請求按照順序執行(因爲是同步請求)。

程序運行共耗時 16.6 秒

下面我們試試 "異步" http 請求:

import asyncio
import httpx
import threading
import time

client = httpx.AsyncClient()

async def async_main(url, sign):
    response = await client.get(url)
    status_code = response.status_code
    print(f'async_main: {threading.current_thread()}: {sign}:{status_code}')


loop = asyncio.get_event_loop()
tasks = [async_main(url='http://www.baidu.com'sign=i) for i in range(200)]
async_start = time.time()
loop.run_until_complete(asyncio.wait(tasks))
async_end = time.time()
loop.close()
print(async_end - async_start)

上述代碼在 async_main 中用 async await 關鍵字實現了 "異步" http,通過 asyncio ( 異步 io 庫請求百度首頁 200 次並打印出了耗時。

運行代碼後可以看到如下輸出(截取了部分關鍵輸出…)

async_main: <_MainThread(MainThread, started 4471512512)>: 56: 200
async_main: <_MainThread(MainThread, started 4471512512)>: 99: 200
async_main: <_MainThread(MainThread, started 4471512512)>: 67: 200
async_main: <_MainThread(MainThread, started 4471512512)>: 93: 200
async_main: <_MainThread(MainThread, started 4471512512)>: 125: 200
async_main: <_MainThread(MainThread, started 4471512512)>: 193: 200
async_main: <_MainThread(MainThread, started 4471512512)>: 100: 200
4.518340110778809

可以看到順序雖然是亂的(56,99,67…) (這是因爲程序在協程間不停切換) 但是主線程並沒有切換 (協程本質還是單線程 )。

程序共耗時 4.5 秒

比起同步請求耗時的 16.6 秒 縮短了接近 73 %!

俗話說得好,一步快,步步快。 在耗時方面,"異步" http 確實比同步 http 快了很多。當然,"協程" 不僅僅能在請求效率方面賦能接口測試, 掌握 "協程" 後,相信小夥伴們的技術水平也能提升一個臺階,從而設計出更優秀的測試框架。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/MZTXAU5-gp_AFiOqM2q9vA