如何递归地返回异步函数

时间:2020-01-08 16:58:13

标签: python python-asyncio

我有一个函数,它递归地尝试从URL检索信息。如果收到的响应不是200,它将重试3次,如果什么也无法返回,则最终返回None。但是,我的问题是,当我通过事件循环运行此函数时,该函数未像正常的递归函数那样再次运行,而是仅返回协程而不是预期的JSON响应或None

async def make_request(session, url, attempt=0):
    async with session.get(url) as response:
        if response.status == 200:
            return await response.json()
        elif attempt < 3:
            return await make_request(session, url, attempt + 1) 
            # When it gets to this line, instead of returning the result of this function, 
            # it returns the coroutine object itself.
        return None

我是否应该事先运行某些文件以确保其正常运行?

1 个答案:

答案 0 :(得分:1)

没有完整的代码示例,无法重现您的错误。无论如何,这里的代码有效:

import asyncio
import aiohttp


async def make_request(session, url, attempt=0):
    async with session.get(url) as response:
        if response.status == 200:
            return await response.json()
        elif attempt < 3:
            print(f'failed #{attempt}')  # to debug, remove later
            return await make_request(session, url, attempt + 1)
        return None


async def main():
    async with aiohttp.ClientSession() as session:
        res = await make_request(session, 'http://httpbin.org/status/404')
        print(res)

        res = await make_request(session, 'http://httpbin.org/json')
        print(res)


asyncio.run(main())

顺便说一句,您可能不想对使用其他人的解决方案感兴趣,而不是尝试编写自己的重试内容,例如:

https://github.com/inyutin/aiohttp_retry

https://github.com/hellysmile/async_retrying