如何在aiohttp请求中实现直到成功的重试循环?现有代码可行吗?
原代码无法实现你的需求,问题如下:
else块里的continue无效,当前没有循环结构,会直接抛出语法错误- 完全没有重试逻辑,无论请求失败、状态码非200还是转换float失败,都会直接返回
None,不会再次尝试请求 data = await response是多余操作,直接用response即可;且response.json()是异步方法,必须加await,否则会抛出错误
修正后的代码(实现无限重试直到成功)
import aiohttp import asyncio async def get_data(session, x): while True: try: async with session.get(url=f'https://api.abc.com/{x}') as response: if response.status_code == 200: # 异步解析JSON响应 json_data = await response.json() # 尝试转换为float类型 result = float(json_data) return result # 状态码非200,打印信息后进入下一次重试 print(f"请求{x}返回状态码{response.status_code},重试中...") except Exception as e: # 捕获所有异常(网络错误、JSON解析失败、float转换失败等) print(f"请求{x}出错:{str(e)},重试中...") # 可选添加延迟,避免频繁请求触发API限流 await asyncio.sleep(1) async def main(datas): async with aiohttp.ClientSession() as session: ret = await asyncio.gather(*[get_data(session, data) for data in datas]) return {datas[i]: ret[i] for i in range(len(datas))} datas = ['x1', 'x2', 'x3', 'x4'] results = asyncio.run(main(datas)) print(results)
关键说明
- 用
while True实现无限循环重试,直到满足条件(状态码200+成功转float)才返回结果 - 统一捕获所有可能的异常,捕获后打印错误信息并继续循环重试
- 修复了
response.json()的异步调用问题,补充了必要的await - 可选添加
await asyncio.sleep(1),避免短时间内高频请求触发API限流机制
内容的提问来源于stack exchange,提问作者anarchy
相关产品推荐
相关产品推荐

