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

Kay*_*Kay 14 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
Run Code Online (Sandbox Code Playgroud)

如果响应的状态代码不是 200 或 429,我希望所有请求最多可退出 10 次。

iny*_*tin 16

我做了一个简单的库,可以帮助你: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()
Run Code Online (Sandbox Code Playgroud)

而是google.com使用你自己的url

  • 当有很多 URL 并使用 asyncio.gather 时,如何使用它? (2认同)

Mik*_*mov 13

默认情况下,aiohttp 不会引发非 200 状态的异常。你应该改变它通过raise_for_status=Truedoc):

async with session.get(url, params=params, headers=headers, raise_for_status=True) as response:
Run Code Online (Sandbox Code Playgroud)

它应该为任何 400 或更高的状态引发异常,从而触发backoff.

代码 2xx 不应该重试,因为这些不是错误


无论如何,如果您仍然想为“200 或 429 以外的”加注,您可以手动进行:

if response.status not in (200, 429,):
     raise aiohttp.ClientResponseError()
Run Code Online (Sandbox Code Playgroud)

  • @Kulasangar,您可以使用 aysnc_retrying 库来实现 https://pypi.org/project/async_retrying/ (2认同)