gpt4 book ai didi

python - Aiohttp尝试而请求不成功

转载 作者:行者123 更新时间:2023-12-03 19:13:21 24 4
gpt4 key购买 nike

我有那个代码

async with aiohttp.ClientSession() as session:
content = 'none'
while content == 'none':
try:
async with session.get(url) as resp:
resp.raise_for_status()
content = await resp.json()
except aiohttp.ClientError:
await asyncio.sleep(1)
except Exception as e:
print(e)
await asyncio.sleep(1)

我想在结果良好时发出请求,但如果我编译它,有时结果是“无”。怎么弄好点。

最佳答案

我用 async-retrying 为了那个原因。你用 @retry 标记请求函数装饰器,如果引发异常,它将重新运行。例子:

import asyncio
import aiohttp
from async_retrying import retry


@retry(attempts=100)
async def req(session, url):
async with session.get(url) as resp:
resp.raise_for_status()
return await resp.json()


async def main():
async with aiohttp.ClientSession() as session:
payload = await req(session, "http://eu.httpbin.org/get")
print("payload received:", payload)


if __name__ == "__main__":
asyncio.run(main())

关于python - Aiohttp尝试而请求不成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61444082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com