HTTPX支持通過?proxies
?參數(shù)設(shè)置 HTTP 代理,該參數(shù)將在client初始化或頂級API函數(shù)(如HTTPX)上傳遞。
要將所有流量(HTTP 和 HTTPS)路由到位于 ?http://localhost:8030
?的代理,請將代理 URL 傳遞給?Client
?...
with httpx.Client(proxies="http://localhost:8030") as client:
...
對于更高級的用例,請傳遞代理?dict
?(dict為python的字典類型,也可翻譯為字典,此處不做翻譯)。例如,要將 HTTP 和 HTTPS 請求路由到 2 個不同的代理,分別位于?http://localhost:8030
?和?http://localhost:8031
? ,請傳遞代理 URL 的?dict
?:
proxies = {
"http://": "http://localhost:8030",
"https://": "http://localhost:8031",
}
with httpx.Client(proxies=proxies) as client:
...
有關(guān)代理路由的詳細(xì)信息,請參閱本章節(jié)的 路由 部分。
補(bǔ)充:
在大多數(shù)情況下,?https://key
?的代理URL應(yīng)該使用?http://scheme
?(這不是拼寫錯誤?。?。
這是因為HTTP代理需要啟動與代理服務(wù)器的連接。雖然您的代理可能支持通過HTTPS執(zhí)行,但大多數(shù)代理僅支持通過HTTP執(zhí)行。
有關(guān)詳細(xì)信息,請參閱本章節(jié)的 轉(zhuǎn)發(fā)與隧道。
代理憑據(jù)可以作為代理 URL 的?userinfo
?部分傳遞。例如:
proxies = {
"http://": "http://username:password@localhost:8030",
# ...
}
HTTPX提供了細(xì)粒度的控制,用于決定哪些請求可以通過代理,哪些不可以通過代理。此過程稱為代理路由。
代理字典將URL模式(“代理密鑰”)映射到代理URL。HTTPX將請求的URL與代理密鑰進(jìn)行匹配,以決定應(yīng)該使用哪個代理(如果有的話)。從最特定的代理密鑰(例如?https://<domain>:<port>
?)到最不特定的代理密鑰(例如?https:///
?)進(jìn)行匹配。
HTTPX 支持基于scheme、域、端口或這些方案的組合的路由代理。
通過代理路由所有內(nèi)容...
proxies = {
"all://": "http://localhost:8030",
}
通過一個代理路由HTTP請求,通過另一個代理路由HTTPS請求...
proxies = {
"http://": "http://localhost:8030",
"https://": "http://localhost:8031",
}
代理域“example.com”上的所有請求,讓其他請求通過...
proxies = {
"all://example.com": "http://localhost:8030",
}
代理HTTP請求在域“example.com”上,讓HTTPS和其他請求通過...
proxies = {
"http://example.com": "http://localhost:8030",
}
代理所有請求到“example.com”及其子域,讓其他請求通過...
proxies = {
"all://*example.com": "http://localhost:8030",
}
將所有請求代理到“example.com”的嚴(yán)格子域,讓“example.com”等請求通過...
proxies = {
"all://*.example.com": "http://localhost:8030",
}
在端口1234上代理HTTPS請求到“example.com”...
proxies = {
"https://example.com:1234": "http://localhost:8030",
}
代理端口 1234 上的所有請求...
proxies = {
"all://*:1234": "http://localhost:8030",
}
還可以定義不應(yīng)通過代理路由的請求。
為此,請傳遞None作為代理URL。例如...
proxies = {
# Route requests through a proxy by default...
"all://": "http://localhost:8031",
# Except those for "example.com".
"all://example.com": None,
}
您可以組合上述路由功能來構(gòu)建復(fù)雜的代理路由配置。例如。。。
proxies = {
# Route all traffic through a proxy by default...
"all://": "http://localhost:8030",
# But don't use proxies for HTTPS requests to "domain.io"...
"https://domain.io": None,
# And use another proxy for requests to "example.com" and its subdomains...
"all://*example.com": "http://localhost:8031",
# And yet another proxy if HTTP is used,
# and the "internal" subdomain on port 5550 is requested...
"http://internal.example.com:5550": "http://localhost:8032",
}
HTTP代理也可以通過環(huán)境變量進(jìn)行配置,盡管其細(xì)粒度控制較少。
有關(guān)詳細(xì)信息,請參閱有關(guān) HTTP_PROXY
,HTTPS_PROXY
,ALL_PROXY
的文檔。
注意
本節(jié)介紹高級代理概念和功能。
通常,通過代理發(fā)出 HTTP 請求的流程如下:
步驟 2 的確切執(zhí)行方式取決于使用兩種代理機(jī)制中的哪一種:
如果您在設(shè)置代理時遇到問題,請參閱我們的疑難解答指南。
更多建議: