Skip to main content
 首页 » 编程设计

python之处理 aiohttp 中的错误请求

2024年11月24日13bonelee

我正在尝试找出一种方法来使用 aiohttp 在异步函数中处理来自 API 的错误请求。这是我要测试的:

async def fetch(session): 
    url = 'http://httpbin.org/status/404' 
    async with session.request('GET', url) as response: 
        if response.status == 200: 
            try: 
                r = await response.json() 
                return r 
            except ValueError: 
                return 
        else: 
            return None 
 
async def fetch_all(project_list): 
    output = [] 
    async with ClientSession() as session: 
        tasks = [asyncio.ensure_future(fetch(session, project)) for project in project_list] 
        for future in await asyncio.gather(*tasks): 
            output += future 
    return output 
 
def get_data(project_list): 
    loop = asyncio.get_event_loop() 
    futures = asyncio.ensure_future(fetch_all(project_list)) 
    output = loop.run_until_complete(futures) 
    return output 

在此示例中,project_list 只是一个整数列表。

在这种情况下,fetch() 应该返回 none,因为响应无疑是 404。问题出现在 fetch_all() 中,我将它告诉 += future 。我收到一个 TypeError: 'coroutine' object is not iterable. 基本上我希望它不返回任何内容,在这种情况下,+= 不会返回任何内容。在一个完美的世界中,我每次都会收到正确的 json 响应,但我想考虑一个随机实例,其中我从服务器收到错误响应。

根据我的阅读,@asyncio.coroutine 会返回 None 但 async 值必须是 awaited 如果我理解的话它正确。

请您参考如下方法:

首先,如果要使用gather,则不需要将task包装在ensure_future中。其次,您正尝试使用 2 个参数添加提取任务: session 和项目,但您的提取函数定义中只有 session 。您还可以更改的另一件事是删除迭代收集结果的循环,因为它已经为您提供了您想要返回的输出。 代码将是这样的:

async def fetch(session, project): 
    url = 'http://httpbin.org/status/404' 
    async with session.request('GET', url) as response: 
        if response.status == 200: 
            try: 
                return await response.json() 
 
            except ValueError: 
                pass 
 
        return None 
 
async def fetch_all(project_list): 
    output = [] 
    async with ClientSession() as session: 
        tasks = [fetch(session, project) for project in project_list] 
        return await asyncio.gather(*tasks) 
 
def get_data(project_list): 
    loop = asyncio.get_event_loop() 
    output = loop.run_until_complete(futures) 
    return output 

至于建议:仅当您想立即运行协程时才使用 ensure_future,但结果仅在将来需要。