HTTPSConnectionPool(host='www.dmxapi.cn', port=443): Read timed out. (read timeo...
错误信息
HTTPSConnectionPool(host='www.dmxapi.cn', port=443): Read timed out. (read timeout=120)
AI 解决方案
错误分析
1. 错误翻译
原文:Read timed out. (read timeout=120)
译文:读取超时。(读取超时时间 = 120秒)
2. 原因分析
这是一个HTTP(S)连接读取超时错误。根本原因是客户端(如Python的
requests库)尝试向服务器www.dmxapi.cn:443发送请求,并在等待服务器响应的过程中达到了预设的120秒超时限制,服务器未能在此时间窗口内返回完整响应。3. 解决方案
最直接的解决方案是适当增加超时时间。
方案一:增加总超时时间(推荐)
import requests
# 设置连接超时和读取超时(总超时时间)
# connect timeout: 建立连接的时间上限
# read timeout: 等待服务器响应的总时间上限
try:
response = requests.get('https://www.dmxapi.cn', timeout=(10, 180)) # 连接10秒,读取180秒
print(response.text)
except requests.exceptions.Timeout as e:
print(f"请求超时:{e}")
except Exception as e:
print(f"其他错误:{e}")
方案二:同时监控网络稳定性
如果增加超时时间后问题依然存在,可能是网络或服务器端的问题,需要更健壮的重试逻辑。
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retries = Retry(total=3, # 总重试次数
backoff_factor=1, # 重试间隔的指数基数
status_forcelist=[500, 502, 503, 504]) # 遇到这些状态码也重试
session.mount('http://', HTTPAdapter(max_retries=retries))
session.mount('https://', HTTPAdapter(max_retries=retries))
try:
# 使用带有重试机制的会话
response = session.get('https://www.dmxapi.cn', timeout=(10, 180))
response.raise_for_status() # 检查HTTP状态码
print("请求成功")
except requests.exceptions.RequestException as e:
print(f"请求失败:{e}")
4. ️ 预防措施
tenacity 等第三方库简化重试和熔断逻辑的实现。