Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何递归返回异步函数_Python_Python Asyncio - Fatal编程技术网

Python 如何递归返回异步函数

Python 如何递归返回异步函数,python,python-asyncio,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.stat

我有一个函数,它递归地尝试从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
async def make_请求(会话、url、尝试=0):
以session.get(url)作为响应的异步:
如果response.status==200:
return wait response.json()
elif尝试<3:
返回等待发出请求(会话、url、尝试+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())
导入异步IO
进口aiohttp
异步def生成请求(会话、url、尝试=0):
以session.get(url)作为响应的异步:
如果response.status==200:
return wait response.json()
elif尝试<3:
打印(f'failed#{trust}')#要调试,请稍后删除
返回等待发出请求(会话、url、尝试+1)
一无所获
异步def main():
与aiohttp.ClientSession()作为会话异步:
res=等待发出请求(会话)http://httpbin.org/status/404')
打印(res)
res=等待发出请求(会话)http://httpbin.org/json')
打印(res)
asyncio.run(main())
顺便说一句,您可能对使用他人的解决方案感兴趣,而不是尝试编写自己的重试内容,例如:


向事件循环添加异步函数时,似乎缺少括号。为什么要使用递归?