Python调用API遇Max retries exceeded错误,求技术解决方案
问题描述
调用API获取数据时遇到如下错误:
Max retries exceeded with url: /api/search?accept=application%2Fjson&Authorization=Bearer......
使用的Python代码:
token = 'aagagagagagagagaggagagag' def get_val (ont, term): #set the url url = 'https://host:port/api/search' #set the header Authorization = 'Bearer ' + token header = { 'accept': */*, 'Authorization': Authorization, } #set the parameters params = {'ontology': ont, 'q': term, 'header':header} #send request response = requests.get(url, header) get_val('mesh', 'ibu')
对应的curl命令:
curl -X 'GET' \ 'https://host:port/api/search?from=0&ontology=mesh&q=ibu&size=10' \ -H 'accept: */*' \ -H 'Authorization: Bearer <token>'
解决方案
你的Python代码存在多处问题,修正后可解决重试错误:
- 修复语法错误:
header字典里的accept值需用字符串包裹,改为'*/*',否则会触发语法错误。 - 修正请求参数传递逻辑:
params不需要包含header,请求头是requests.get的独立参数,不属于URL查询参数。- 调用
requests.get时,参数名应为headers(复数形式),而非header。 - 必须将
params参数传入get方法,否则URL不会带上ontology、q这些必要查询参数,和curl的请求格式无法对齐。
- 添加重试与超时机制:重试错误多与连接超时、请求失败有关,配置自动重试和超时时间可避免这类问题。
修正后的代码:
import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry token = 'aagagagagagagagaggagagag' def get_val(ont, term): url = 'https://host:port/api/search' # 配置自动重试策略 session = requests.Session() retry = Retry( total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504] ) adapter = HTTPAdapter(max_retries=retry) session.mount('https://', adapter) # 设置请求头 headers = { 'accept': '*/*', 'Authorization': f'Bearer {token}' } # 设置查询参数,和curl保持一致 params = { 'ontology': ont, 'q': term, 'from': 0, 'size': 10 } try: # 发送请求并设置超时 response = session.get(url, headers=headers, params=params, timeout=10) # 主动触发HTTP错误,便于排查问题 response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"请求失败: {e}") return None get_val('mesh', 'ibu')
额外说明
- 重试策略:通过
Session和Retry配置针对限流、服务器错误的自动重试,backoff_factor实现指数退避,避免频繁请求触发更严格的限制。 - 超时设置:添加
timeout参数防止请求长时间挂起导致重试次数耗尽。 raise_for_status():如果返回4xx/5xx状态码会抛出异常,可快速定位是权限问题、参数错误还是服务器故障。
内容的提问来源于stack exchange,提问作者rshar
相关产品推荐
相关产品推荐

