我正在使用一个 API,有时它会返回一些奇怪的状态代码,这些代码可以通过简单地重试相同的请求来修复。我正在使用 aiohttp 异步向该 api 提交请求。
我也在使用退避库来重试请求,但是在 401 状态响应时似乎仍然没有重试请求。
@backoff.on_exception(backoff.expo, aiohttp.ClientError, max_tries=11, max_time=60)
async def get_user_timeline(self, session, user_id, count, max_id, trim_user, include_rts, tweet_mode):
params = {
'user_id': user_id,
'trim_user': trim_user,
'include_rts': include_rts,
'tweet_mode': tweet_mode,
'count': count
}
if (max_id and max_id != -1):
params.update({'max_id': max_id})
headers = {
'Authorization': 'Bearer {}'.format(self.access_token)
}
users_lookup_url = "/1.1/statuses/user_timeline.json"
url = self.base_url + users_lookup_url
async with session.get(url, params=params, headers=headers) as response:
result = await response.json()
response = {
'result': result,
'status': response.status,
'headers': response.headers
}
return response
如果响应的状态代码不是 200 或 429,我希望所有请求都退回最多 10 次。
最佳答案
我做了一个简单的库,可以帮助你:
https://github.com/inyutin/aiohttp_retry
像这样的代码应该可以解决您的问题:
from aiohttp import ClientSession
from aiohttp_retry import RetryClient
statuses = {x for x in range(100, 600)}
statuses.remove(200)
statuses.remove(429)
async with ClientSession() as client:
retry_client = RetryClient(client)
async with retry_client.get("https://google.com", retry_attempts=10, retry_for_statuses=statuses) as response:
text = await response.text()
print(text)
await retry_client.close()
google.com
使用您自己的 url
关于python - 如何根据状态码重试异步 aiohttp 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56152651/