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

标签 python python-3.x python-asyncio 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 次。

最佳答案

我做了一个简单的库,可以帮助你:
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/

相关文章:

python-3.x - Python 异步 : Waiting for stdin input while doing other stuff

python - 确保 aiohttp/asyncio 中递归函数的 future

python - Keras reshape 输入 LSTM

python - 分解串联列表或数据框,python

python - 格式化程序 %r 和 %s - 理论上的差异,但这个脚本另有说明

python - Pandas :计算一行与所有其他行之间的差异

python - 将项目添加到对象列表

Python - 将整数列表拆分为正数和负数

python - 在数组中搜索一个值,然后从其他相同长度的数组/ndarrays 中打印相应的值

python - asyncio.wait_for 不会传播 CancelledError,如果在取消之前等待 future 为 "done"