如何根据状态码重试异步 aiohttp 请求

新手上路,请多包涵

我正在使用一个 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 次。

原文由 Kay 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
1 个回答

我做了一个简单的库,可以帮助你:

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

原文由 inyutin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题