使用Semaphore时如何存储asyncio.gather()响应?为何返回None?
为什么asyncio.gather()返回的结果全是None,明明fetch函数能获取到响应?
运行代码
import asyncio from aiohttp import ClientSession async def fetch(url, session): async with session.get(url) as response: data = await response.read() print(data) return data async def bound_fetch(sem, url, session): async with sem: await fetch(url, session) async def run(r): url = "http://localhost:8080" tasks = [] sem = asyncio.Semaphore(1000) async with ClientSession() as session: for i in range(r): task = asyncio.ensure_future(bound_fetch(sem, url, session)) tasks.append(task) responses = asyncio.gather(*tasks) await responses print(responses.result()) number = 10 loop = asyncio.get_event_loop() future = asyncio.ensure_future(run(number)) loop.run_until_complete(future)
代码输出
b'<!DOCTYPE html>\n<html>\n<body>\n\n<h1>Hello World</h1>\n\n</body>\n</html>' b'<!DOCTYPE html>\n<html>\n<body>\n\n<h1>Hello World</h1>\n\n</body>\n</html>' b'<!DOCTYPE html>\n<html>\n<body>\n\n<h1>Hello World</h1>\n\n</body>\n</html>' b'<!DOCTYPE html>\n<html>\n<body>\n\n<h1>Hello World</h1>\n\n</body>\n</html>' b'<!DOCTYPE html>\n<html>\n<body>\n\n<h1>Hello World</h1>\n\n</body>\n</html>' b'<!DOCTYPE html>\n<html>\n<body>\n\n<h1>Hello World</h1>\n\n</body>\n</html>' b'<!DOCTYPE html>\n<html>\n<body>\n\n<h1>Hello World</h1>\n\n</body>\n</html>' b'<!DOCTYPE html>\n<html>\n<body>\n\n<h1>Hello World</h1>\n\n</body>\n</html>' b'<!DOCTYPE html>\n<html>\n<body>\n\n<h1>Hello World</h1>\n\n</body>\n</html>' b'<!DOCTYPE html>\n<html>\n<body>\n\n<h1>Hello World</h1>\n\n</body>\n</html>' [None, None, None, None, None, None, None, None, None, None]
疑问
明明fetch()函数能获取到预期的请求响应,为何asyncio.gather()返回的responses中没有实际响应内容,反而全是None?
解答
问题出在bound_fetch函数上:它仅调用了await fetch(url, session),但没有将fetch返回的响应数据传递出去。Python中函数如果没有显式的return语句,默认返回None,因此asyncio.gather收集到的是10个bound_fetch的默认返回值,自然全为None。
只需修改bound_fetch函数,让它返回fetch的执行结果即可:
async def bound_fetch(sem, url, session): async with sem: return await fetch(url, session)
修改后,asyncio.gather就能正确收集到每个fetch返回的响应数据了。
内容的提问来源于stack exchange,提问作者kelsonic
相关产品推荐
相关产品推荐

