阅读(3514) (1)

httpx 超时配置

2022-07-20 13:55:27 更新

默认情况下,HTTPX 会小心地在任何地方强制实施超时。

默认行为是在网络不活动5秒后引发​TimeoutException​。

设置和禁用超时

您可以为单个请求设置超时:

# 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上设置默认超时

您可以在​Client​实例上设置超时,这将导致给定的​timeout​用作使用此客户端发出的请求的默认值:

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 还允许您以更细粒度的细节指定超时行为。

可能会发生四种不同类型的超时。这些是连接、读取、写入和池超时。

  • 连接超时指定在建立与所请求主机的套接字连接之前等待的最长时间。如果 HTTPX 在此时间范围内无法连接,则会引发​ConnectTimeout​异常。
  • 读取超时指定等待接收数据块(例如,响应正文块)的最大持续时间。如果 HTTPX 无法在此时间范围内接收数据,则会引发​ReadTimeout​异常。
  • 写入超时指定等待发送数据块(例如,请求正文块)的最大持续时间。如果 HTTPX 无法在此时间范围内发送数据,则会引发​WriteTimeout​异常。
  • 池超时指定等待从连接池获取连接的最大持续时间。如果 HTTPX 无法在此时间范围内获取连接,则会引发​PoolTimeoutlimits​异常。此处的相关配置是连接池中允许的最大连接数,该连接由参数配置。

您可以为这些值中的任何一个配置超时行为...

# 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/')