首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对某些状态代码重试异步aiohttp请求

对某些状态代码重试异步aiohttp请求
EN

Stack Overflow用户
提问于 2022-03-12 18:04:00
回答 1查看 690关注 0票数 1

使用aiohttp重试异步API调用的最佳方法是什么?我想重试对标准套接字错误、超时错误等以及某些状态代码500, 501的请求。我试过使用异步,但无法让它起作用:

代码语言:javascript
复制
import asyncio
from aiohttp import ClientSession
from aiohttp_retry import RetryClient

# Async single retry fetch
async def async_retry_fetch(url, retry_client):
    async with retry_client.get(url, retry_attempts=3, retry_for_status=[500, 501]) as response:
        try:
            data = await response.json()
        except Exception as e:
            raise Exception("Could not convert json")
    return data

async def main():
    urls = [
        "https://httpstat.us/200",
        "https://httpstat.us/500"
    ]
    api_calls = []
    async with ClientSession() as session:
        retry_client = RetryClient(session)
        for url in urls:
            api_calls.append(async_retry_fetch(url, retry_client))
    res = await asyncio.gather(*api_calls, return_exceptions=True)
    print("RESULT", res)

asyncio.run(main())

输出:

代码语言:javascript
复制
RESULT [AttributeError("'ClientSession' object has no attribute 'debug'"), AttributeError("'ClientSession' object has no attribute 'debug'")]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-13 03:05:03

看起来您已经安装了aiohttp_retry 2.x版

但是您可以为1.2版使用参数,这将给出AttributeError

旧版本可以使用

代码语言:javascript
复制
get(..., retry_attempts=3)

但是新版本需要

代码语言:javascript
复制
get(..., retry_options=ExponentialRetry(attempts=3)

代码语言:javascript
复制
RetryClient(..., retry_options=ExponentialRetry(attempts=3))

但是attempts in RetryClient有默认值3,所以您可以跳过它。

另一个问题是RetryClient()不能将session作为参数。

而且它不需要它,因为它在__init__中创建了自己的__init__

请参阅源代码

这对我来说很管用:

代码语言:javascript
复制
import asyncio
from aiohttp_retry import RetryClient, ExponentialRetry

class MyLogger():
    def debug(self, *args, **kwargs):
        print('[debug]:', *args, **kwargs)
    
async def async_retry_fetch(url, retry_client):

    retry_options = ExponentialRetry(attempts=3)

    #async with retry_client.get(url) as response:
    # OR
    async with retry_client.get(url, retry_options=ExponentialRetry(attempts=3), raise_for_status=[500, 501]) as response:
        try:
            data = await response.json()
        except Exception as e:
            raise Exception("Could not convert json")

    return data

async def main():
    urls = [
        "https://httpstat.us/200",
        "https://httpstat.us/500",
        "https://httpstat.us/501",
        "https://httpbin.org/status/500",
        "https://httpbin.org/status/501",
        "https://httpbin.org/json"
    ]

    #async with RetryClient(logger=MyLogger(), retry_options=ExponentialRetry(attempts=3), raise_for_status=[500, 501]) as retry_client:
    # OR
    async with RetryClient(logger=MyLogger()) as retry_client:
        api_calls = []
        
        for url in urls:
            api_calls.append(async_retry_fetch(url, retry_client))
            
        res = await asyncio.gather(*api_calls, return_exceptions=True)
 
        for item in res:
            print(item)
            print('---')

# --- start ---

asyncio.run(main())

结果:

代码语言:javascript
复制
[debug]: Attempt 0 out of 3
[debug]: Attempt 0 out of 3
[debug]: Attempt 0 out of 3
[debug]: Attempt 0 out of 3
[debug]: Attempt 0 out of 3
[debug]: Attempt 0 out of 3
[debug]: Attempt 1 out of 3
[debug]: Attempt 1 out of 3
[debug]: Attempt 1 out of 3
[debug]: Attempt 1 out of 3
[debug]: Attempt 2 out of 3
[debug]: Attempt 2 out of 3
[debug]: Attempt 2 out of 3
[debug]: Attempt 2 out of 3
Could not convert json
---
500, message='Internal Server Error', url=URL('https://httpstat.us/500')
---
501, message='Not Implemented', url=URL('https://httpstat.us/501')
---
500, message='INTERNAL SERVER ERROR', url=URL('https://httpbin.org/status/500')
---
501, message='NOT IMPLEMENTED', url=URL('https://httpbin.org/status/501')
---
{'slideshow': {'author': 'Yours Truly', 'date': 'date of publication', 'slides': [{'title': 'Wake up to WonderWidgets!', 'type': 'all'}, {'items': ['Why <em>WonderWidgets</em> are great', 'Who <em>buys</em> WonderWidgets'], 'title': 'Overview', 'type': 'all'}], 'title': 'Sample Slide Show'}}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71452063

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档