如何在aiohttp请求中添加尝试直到成功循环

问题描述 投票:0回答:1

我有以下代码,

import aiohttp
import asyncio

async def get_data(session, x):
    try:
        async with session.get(url=f'https://api.abc.com/{x}') as response:
            data = await response.json()
            if data.status_code == 200:
                data = float(data)
                return data
            else:
                continue
    except Exception as e:
        print("Unable to get url {} due to {}.".format(x, e.__class__))
        return None

async def main(datas):
    async with aiohttp.ClientSession() as session:
        ret = await asyncio.gather(*[get_data(session, data) for data in datas])
        return {datas[i]: ret[i] for i in range(len(datas))}  # Return the results as a dictionary

datas = ['x1', 'x2', 'x3', 'x4']
results = asyncio.run(main(datas))

我想查询api直到我得到响应== 200并且我能够得到float(data),如果数据是文本,它将失败。所以它应该尝试 float(data) 直到成功。

如果失败,我想重试,直到成功。

下面的代码可以工作吗?我不习惯异步代码。

import aiohttp
import asyncio

async def get_data(session, x):
    while True:
        try:
            async with session.get(url=f'https://api.abc.com/{x}') as response:
                data = await response.json()
                data = float(data)
                return data #break
        except Exception as e:
            print("Unable to get url {} due to {}.".format(x, e.__class__))
            time.sleep(1)
            continue

async def main(datas):
    async with aiohttp.ClientSession() as session:
        ret = await asyncio.gather(*[get_data(session, data) for data in datas])
        return {datas[i]: ret[i] for i in range(len(datas))}  # Return the results as a dictionary

datas = ['x1', 'x2', 'x3', 'x4']
results = asyncio.run(main(datas))
python asynchronous python-requests python-asyncio aiohttp
1个回答
0
投票
import aiohttp
import asyncio

async def get_data(session, x):
    while True:
        try:
            async with session.get(url=f'https://api.abc.com/{x}') as response:
                if response.status == 200:
                    data = await response.json()
                    try:
                        data = float(data)
                        return data
                    except ValueError:
                        print("Data is not a valid float. Retrying...")
                else:
                    print("Received non-200 status code. Retrying...")
            await asyncio.sleep(1)  # Wait for 1 second before retrying
        except Exception as e:
            print("Unable to get url {} due to {}. Retrying...".format(x, e.__class__))
            await asyncio.sleep(1)  # Wait for 1 second before retrying

async def main(datas):
    async with aiohttp.ClientSession() as session:
        ret = await asyncio.gather(*[get_data(session, data) for data in datas])
        return {datas[i]: ret[i] for i in range(len(datas))}  # Return the results as a dictionary

datas = ['x1', 'x2', 'x3', 'x4']
results = asyncio.run(main(datas))

在更新后的 get_data 函数中,我们有一个 while True 循环,它将不断重试,直到满足条件。当 API 响应的状态代码为 200 时,我们尝试使用 float(data) 将数据转换为浮点数。如果成功,我们返回结果。如果数据不是有效的浮点数(引发 ValueError),我们会打印一条消息并重试。

© www.soinside.com 2019 - 2024. All rights reserved.