httpx 超時(shí)配置

2022-07-26 14:07 更新

默認(rèn)情況下,HTTPX 會(huì)小心地在任何地方強(qiáng)制實(shí)施超時(shí)。

默認(rèn)行為是在網(wǎng)絡(luò)不活動(dòng)5秒后引發(fā)?TimeoutException?。

設(shè)置和禁用超時(shí)

您可以為單個(gè)請求設(shè)置超時(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)

或者禁用單個(gè)請求的超時(shí):

# 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è)置默認(rèn)超時(shí)

您可以在?Client?實(shí)例上設(shè)置超時(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.

微調(diào)配置

HTTPX 還允許您以更細(xì)粒度的細(xì)節(jié)指定超時(shí)行為。

可能會(huì)發(fā)生四種不同類型的超時(shí)。這些是連接、讀取、寫入和池超時(shí)。

  • 連接超時(shí)指定在建立與所請求主機(jī)的套接字連接之前等待的最長時(shí)間。如果 HTTPX 在此時(shí)間范圍內(nèi)無法連接,則會(huì)引發(fā)?ConnectTimeout?異常。
  • 讀取超時(shí)指定等待接收數(shù)據(jù)塊(例如,響應(yīng)正文塊)的最大持續(xù)時(shí)間。如果 HTTPX 無法在此時(shí)間范圍內(nèi)接收數(shù)據(jù),則會(huì)引發(fā)?ReadTimeout?異常。
  • 寫入超時(shí)指定等待發(fā)送數(shù)據(jù)塊(例如,請求正文塊)的最大持續(xù)時(shí)間。如果 HTTPX 無法在此時(shí)間范圍內(nèi)發(fā)送數(shù)據(jù),則會(huì)引發(fā)?WriteTimeout?異常。
  • 池超時(shí)指定等待從連接池獲取連接的最大持續(xù)時(shí)間。如果 HTTPX 無法在此時(shí)間范圍內(nèi)獲取連接,則會(huì)引發(fā)?PoolTimeoutlimits?異常。此處的相關(guān)配置是連接池中允許的最大連接數(shù),該連接由參數(shù)配置。

您可以為這些值中的任何一個(gè)配置超時(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/')


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)