通過(guò) HTTPS 發(fā)出請(qǐng)求時(shí),HTTPX 需要驗(yàn)證所請(qǐng)求主機(jī)的身份。為此,它使用由受信任的證書(shū)頒發(fā)機(jī)構(gòu) (CA) 提供的 SSL 證書(shū)捆綁包(也稱為 CA 捆綁包)。
默認(rèn)情況下,HTTPX 使用 Certifi 提供的 CA 捆綁包。在大多數(shù)情況下,這是您想要的,即使某些高級(jí)情況可能要求您使用一組不同的證書(shū)。
如果要使用自定義 CA 捆綁包,可以使用?verify
?參數(shù)。
import httpx
r = httpx.get("https://example.org", verify="path/to/client.pem")
或者,也可以使用標(biāo)準(zhǔn)庫(kù) ?ssl.SSLContext
?。
>>> import ssl
>>> import httpx
>>> context = ssl.create_default_context()
>>> context.load_verify_locations(cafile="/tmp/client.pem")
>>> httpx.get('https://example.org', verify=context)
<Response [200 OK]>
我們還包含一個(gè)幫助程序函數(shù),用于創(chuàng)建正確配置的?SSLContext
?實(shí)例。
>>> context = httpx.create_ssl_context()
?create_ssl_context
?函數(shù)接受與 ?httpx.Client
?或?httpx.AsyncClient
?相同的 SSL 配置參數(shù)集(?trust_env
?、?verify
?、?cert
?和?http2
?參數(shù))
>>> import httpx
>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")
>>> httpx.get('https://example.org', verify=context)
<Response [200 OK]>
或者您也可以完全禁用SSL驗(yàn)證,這是不推薦的。
import httpx
r = httpx.get("https://example.org", verify=False)
如果您使用的是 Client()
實(shí)例,則應(yīng)在實(shí)例化客戶端時(shí)傳遞任何 SSL 設(shè)置。
client = httpx.Client(verify=False)
?client.get(...)
?方法和其他請(qǐng)求方法不支持基于每個(gè)請(qǐng)求更改 SSL 設(shè)置。如果在不同情況下需要不同的 SSL 設(shè)置,則應(yīng)使用多個(gè)?Client
?實(shí)例,每個(gè)?Client
?實(shí)例具有不同的設(shè)置。然后,每個(gè)?Client
?將在該池中的所有連接上使用具有特定固定 SSL 配置的獨(dú)立連接池。
您還可以指定要用作客戶端證書(shū)的本地證書(shū),可以是 SSL 證書(shū)文件的路徑,也可以是兩元組(證書(shū)文件、密鑰文件),也可以是三元組(證書(shū)文件、密鑰文件、密碼)
import httpx
r = httpx.get("https://example.org", cert="path/to/client.pem")
或者
>>> cert = ("path/to/client.pem", "path/to/client.key")
>>> httpx.get("https://example.org", cert=cert)
<Response [200 OK]>
或
>>> cert = ("path/to/client.pem", "path/to/client.key", "password")
>>> httpx.get("https://example.org", cert=cert)
<Response [200 OK]>
向本地服務(wù)器(如 ?localhost
? 上運(yùn)行的開(kāi)發(fā)服務(wù)器)發(fā)出請(qǐng)求時(shí),通常會(huì)使用未加密的 HTTP 連接。
如果確實(shí)需要與本地服務(wù)器建立 HTTPS 連接(例如,測(cè)試僅 HTTPS 服務(wù)情況),則需要?jiǎng)?chuàng)建并使用自己的證書(shū)。這是一種方法:
--ssl-keyfile
? 和 ?--ssl-certfile
?選項(xiàng)。client.pem
? 中的證書(shū):>>> import httpx
>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")
>>> r
Response <200 OK>
更多建議: