为了在 JSON 解码错误时重新尝试请求,可以使用 AIOHTTP RetryClient 和 AIOHTTP JSON Decoder 的组合。以下是一个示例代码,该代码使用重试客户端并使用包含重试逻辑的自定义 JSON 解码器。
import aiohttp
import json
from aiohttp_retry import RetryClient
class CustomJSONDecoder:
def __init__(self, max_retries=3):
self.max_retries = max_retries
async def __call__(self, response):
try:
return await response.json()
except json.JSONDecodeError as e:
if response.request_info.method not in ("GET", ):
raise e
for i in range(self.max_retries):
async with aiohttp.ClientSession() as session:
retry_response = await session.get(response.url)
try:
return await retry_response.json()
except json.JSONDecodeError:
pass
return {}
async with RetryClient() as session:
session._json_decoder = CustomJSONDecoder()
async with session.get('https://example.com/api') as response:
data = await response.json()