默認(rèn)情況下,HTTPX 會小心地在任何地方強(qiáng)制實施超時。
默認(rèn)行為是在網(wǎng)絡(luò)不活動5秒后引發(fā)?TimeoutException
?。
您可以為單個請求設(shè)置超時:
# Using the top-level API:
httpx.get('http://example.com/api/v1/example', timeout=10.0)
# Using a client instance:
with httpx.Client() as client:
client.get("http://example.com/api/v1/example", timeout=10.0)
或者禁用單個請求的超時:
# Using the top-level API:
httpx.get('http://example.com/api/v1/example', timeout=None)
# Using a client instance:
with httpx.Client() as client:
client.get("http://example.com/api/v1/example", timeout=None)
您可以在?Client
?實例上設(shè)置超時,這將導(dǎo)致給定的?timeout
?用作使用此客戶端發(fā)出的請求的默認(rèn)值:
client = httpx.Client() # Use a default 5s timeout everywhere.
client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.
client = httpx.Client(timeout=None) # Disable all timeouts by default.
HTTPX 還允許您以更細(xì)粒度的細(xì)節(jié)指定超時行為。
可能會發(fā)生四種不同類型的超時。這些是連接、讀取、寫入和池超時。
ConnectTimeout
?異常。ReadTimeout
?異常。WriteTimeout
?異常。PoolTimeoutlimits
?異常。此處的相關(guān)配置是連接池中允許的最大連接數(shù),該連接由參數(shù)配置。您可以為這些值中的任何一個配置超時行為...
# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.
timeout = httpx.Timeout(10.0, connect=60.0)
client = httpx.Client(timeout=timeout)
response = client.get('http://example.com/')
更多建議: