这是我要运行的代码:
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>nn<h1>Hello World</h1>nn</body>n</html>'
b'<!DOCTYPE html>n<html>n<body>nn<h1>Hello World</h1>nn</body>n</html>'
b'<!DOCTYPE html>n<html>n<body>nn<h1>Hello World</h1>nn</body>n</html>'
b'<!DOCTYPE html>n<html>n<body>nn<h1>Hello World</h1>nn</body>n</html>'
b'<!DOCTYPE html>n<html>n<body>nn<h1>Hello World</h1>nn</body>n</html>'
b'<!DOCTYPE html>n<html>n<body>nn<h1>Hello World</h1>nn</body>n</html>'
b'<!DOCTYPE html>n<html>n<body>nn<h1>Hello World</h1>nn</body>n</html>'
b'<!DOCTYPE html>n<html>n<body>nn<h1>Hello World</h1>nn</body>n</html>'
b'<!DOCTYPE html>n<html>n<body>nn<h1>Hello World</h1>nn</body>n</html>'
b'<!DOCTYPE html>n<html>n<body>nn<h1>Hello World</h1>nn</body>n</html>'
[None, None, None, None, None, None, None, None, None, None]
我的问题是为什么responses
不包含请求的实际响应?相反,当我在fetch()期间获得预期的响应时,它为我提供了'None' ?
您的bound_fectch
协例程,用作中间步骤来使用信号量不返回显式结果(因此,隐式地,返回None)。
改成:
async def bound_fetch(sem, url, session):
async with sem:
return await fetch(url, session)
(注意"return"关键字。在with
块内没有关系:退出函数存在块,尽管如此)