Python Backconnect Proxy请求响应超时限制问题求助
请求超时控制失效的修复方案
你的代码存在几处核心问题,导致超时设置无法生效,同时重试逻辑进一步拉长了等待时间,以下是具体修复步骤和优化后的代码:
核心问题诊断
- 适配器挂载顺序错误:后挂载的普通
HTTPAdapter覆盖了带超时设置的TimeoutHTTPAdapter,导致超时规则根本没被应用 - 重试与超时逻辑冲突:
Retry(connect=3)加上退避时间,会让请求在连接失败时重复尝试,总等待时长远超预期 - 代理超时设置不合理:HTTP代理仅设1秒超时,极易触发重试,反而增加整体等待时间
优化后的完整代码
import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry class TimeoutRetryHTTPAdapter(HTTPAdapter): def __init__(self, timeout=5, *args, **kwargs): self.timeout = timeout # 整合重试策略,避免重复挂载适配器 self.retry_strategy = Retry( connect=2, # 减少重试次数,控制总等待时长 backoff_factor=0.3, # 缩短退避间隔 allowed_methods=["POST"], # 仅对POST请求重试(按需调整) status_forcelist=[429, 500, 502, 503, 504] ) kwargs["max_retries"] = self.retry_strategy super().__init__(*args, **kwargs) def send(self, request, **kwargs): # 优先使用请求传入的超时值,否则用适配器默认值 kwargs["timeout"] = kwargs.get("timeout", self.timeout) return super().send(request, **kwargs) def main_request(data, proxy='', type_of_proxy='socks5', user_agent='Mozilla/5.0 (Linux; arm; Android 13; PEPM00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.141 YaBrowser/22.3.6.61.00 SA/3 Mobile Safari/537.36'): s = requests.Session() s.headers.update({'User-Agent': user_agent}) # 挂载整合了超时与重试的适配器(唯一适配器,避免覆盖) adapter = TimeoutRetryHTTPAdapter(timeout=5) s.mount('http://', adapter) s.mount('https://', adapter) # 合理设置代理对应的超时值 timeout_request = 3 if type_of_proxy == 'socks5' else 5 proxies = {} if proxy: proxies = { 'http': f'{type_of_proxy}://{proxy}', 'https': f'{type_of_proxy}://{proxy}' } # 补充原代码中缺失的变量定义 data_1 = data headers_dic = {} # 替换为你的实际请求头 try: page_login = s.post( 'https://my-site.com', data=data_1.encode('utf-8'), verify=False, proxies=proxies, headers=headers_dic, timeout=timeout_request ) page_login.raise_for_status() # 主动抛出HTTP状态码错误 return page_login.text # 返回响应内容(按需调整) except requests.exceptions.ProxyError as e: # SOCKS5代理超时后,重新初始化会话重试一次 s = requests.Session() s.headers.update({'User-Agent': user_agent}) s.mount('http://', TimeoutRetryHTTPAdapter(timeout=5)) s.mount('https://', TimeoutRetryHTTPAdapter(timeout=5)) try: page_login = s.post( 'https://my-site.com', data=data_1.encode('utf-8'), verify=False, proxies=proxies, headers=headers_dic, timeout=timeout_request ) return page_login.text except Exception as retry_err: return f"代理重试失败: {str(retry_err)}" except requests.exceptions.RequestException as e: return f"请求失败: {str(e)}" # 调用示例 print(main_request(data='1', proxy='login:pass@backconnect.proxy.com:16000', type_of_proxy='http'))
关键优化说明
- 整合超时与重试逻辑:将超时设置和重试策略合并到同一个适配器中,避免挂载顺序覆盖问题
- 严格控制重试成本:减少重试次数、缩短退避时间,防止总等待时长失控
- 调整代理超时值:HTTP代理超时放宽到5秒,避免因过短超时触发不必要的重试
- 增加异常处理:针对SOCKS5代理的超时错误,添加一次会话重建重试,提升稳定性
- 补全缺失变量:修复原代码中
data_1、headers_dic未定义的问题
内容的提问来源于stack exchange,提问作者Rew Rok
相关产品推荐
相关产品推荐

