先说结论: httpx 默认给每个请求 5 秒超时,而且这 5 秒不是「整个请求最多 5 秒」,而是拆成四个:connect 管建连,read 管两次收到数据之间的间隔,write 管两次发出数据之间的间隔,pool 管从连接池里等一条空闲连接。只写 timeout=10 等于四个都设 10 秒。实测下来最容易误会的有三点:对方每 0.8 秒挤 1 个字节时,read=2 永远不会触发,20 字节的响应走了 16 秒;上传时如果把 write 设成 None,对方不收数据请求就一直挂着;max_connections 设小了,多出来的请求报的是 PoolTimeout,和网络没关系。下面在 macOS 上用 Python 3.9、httpx 0.28.1 对着本机几个故意「使坏」的测试服务把这些情况逐个复现,输出都是实际跑出来的。
名称 | 管什么 | 超了报什么 |
|---|---|---|
connect | TCP 建连(HTTPS 还包括 TLS 握手) | httpx.ConnectTimeout |
read | 两次收到数据之间最长等多久 | httpx.ReadTimeout |
write | 两次发出数据之间最长等多久 | httpx.WriteTimeout |
pool | 从连接池里拿到一条连接要等多久 | httpx.PoolTimeout |
写法:
import httpx
# 四个都是 10 秒
httpx.get(url, timeout=10)
# 默认 10 秒,单独把 connect 改成 3 秒、read 改成 30 秒
httpx.get(url, timeout=httpx.Timeout(10, connect=3, read=30))
# 完全不设超时(不建议)
httpx.get(url, timeout=None)这四个异常都继承自 httpx.TimeoutException,想统一处理就捕获它。
在本机起四个端口,每个模拟一种「使坏」:
服务端用 socket 加线程写的,核心是这样(完整脚本在文末说明里):
def handle(c):
if mode == 'silent':
time.sleep(30)
elif mode == 'drip':
c.recv(65536)
c.sendall(b'HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\n')
for _ in range(20):
time.sleep(0.8); c.sendall(b'x')
elif mode == 'noread':
c.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096); time.sleep(30)
elif mode == 'slow':
c.recv(65536); time.sleep(2)
c.sendall(b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok')
c.close()default timeout, silent server ReadTimeout 5.09s
read=2, silent server ReadTimeout 2.01s
read=2, drip 1 byte/0.8s (20 bytes) 200 20 bytes 16.12s
connect=2, unroutable 10.255.255.1 ConnectTimeout 2.02s
write=2, 64MB upload, server not reading WriteTimeout 2.03s
write=None, read=3, same upload ReadError 30.02s
max_connections=1, pool=1: req1: 200 2.04s; req2: PoolTimeout 1.00s
max_connections=1, pool=5: req1: 200 2.01s; req2: 200 4.01s逐行看:
timeout,对方不回,5 秒后 ReadTimeout。这一点和 requests 不同:requests 默认不设超时,会一直等。read=2 一次都没触发。真要限制总时长,见下一节。10.255.255.1 是一个不会有回应的内网地址,SYN 发出去没人理,2 秒后 ConnectTimeout。WriteTimeout。None:read 的 3 秒在请求发完之前不起作用,请求一直挂到服务端 30 秒后自己关掉连接,最后报的是 ReadError。上传大文件的服务,write 不要设成 None。pool=1 时等 1 秒就 PoolTimeout;pool=5 时等到第一个请求 2 秒后结束,拿到连接,总共 4 秒成功。httpx 没有「总时限」这个参数。同步代码里可以在读响应体时自己计时:
import time, httpx
def get_with_deadline(url, deadline=10.0):
start = time.monotonic()
with httpx.stream('GET', url, timeout=httpx.Timeout(5, read=3)) as r:
chunks = []
for chunk in r.iter_bytes():
chunks.append(chunk)
if time.monotonic() - start > deadline:
raise TimeoutError(f'超过总时限 {deadline}s')
return r.status_code, b''.join(chunks)这个写法管不到「一个字节都不来」的情况,那种情况交给 read。异步代码更简单,外面套一层 asyncio.wait_for(client.get(url), timeout=10) 就行。
看到 PoolTimeout,先别怀疑网络,它说明并发请求比连接池允许的连接多:
limits = httpx.Limits(max_connections=20, max_keepalive_connections=10)
client = httpx.AsyncClient(limits=limits, timeout=httpx.Timeout(10, pool=30))max_connections 默认 100,max_keepalive_connections 默认 20;max_connections 小、把 pool 调大,让请求排队而不是报错;asyncio.Semaphore 控制并发,池子只是最后一道闸。None;PoolTimeout 是并发超过连接池,先看 Limits,再考虑在外面限并发。测试环境:macOS,Python 3.9.6,httpx 0.28.1,四个测试服务都在 127.0.0.1 上,脚本约 60 行,用标准库 socket 和 threading 写成。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。