python network_error ai_generated true

asyncio.exceptions.TimeoutError: 连接主机 https://slow.example.com 超时

asyncio.exceptions.TimeoutError: Connection timeout to host https://slow.example.com

ID: python/aiohttp-timeout-total

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-03-05首次发现

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —
3.12 active — — —

根因分析

aiohttp ClientTimeout(total 或 sock_connect)在服务器响应之前耗尽;默认 total 为 5 分钟,但 sock_connect 只有 30 秒。

English

The aiohttp ClientTimeout (total or sock_connect) elapsed before the server responded; default total is 5 minutes but sock_connect is only 30s.

generic

解决方案

  1. 95% 成功率
    Configure explicit timeouts:
    
    timeout = aiohttp.ClientTimeout(total=30, connect=5, sock_read=10)
    async with aiohttp.ClientSession(timeout=timeout) as s:
        await s.get(url)
  2. 90% 成功率
    Wrap with asyncio.wait_for for a per-call ceiling:
    
    await asyncio.wait_for(session.get(url), timeout=15)
  3. 88% 成功率
    Use aiohttp-retry for exponential backoff on TimeoutError.

无效尝试

常见但无效的做法:

  1. 85% 失败

    Requests hang forever on dead servers, exhausting the connection pool.

  2. 60% 失败

    Masks slow endpoints but ties up sockets and worker slots.

  3. 70% 失败

    Hammers an already-slow server and can trigger rate limits.