【发布时间】:2018-05-05 14:24:23
【问题描述】:
我正在使用 aiohttp 下载图像,并且想知道是否有办法限制尚未完成的打开请求的数量。这是我目前拥有的代码:
async def get_images(url, session):
chunk_size = 100
# Print statement to show when a request is being made.
print(f'Making request to {url}')
async with session.get(url=url) as r:
with open('path/name.png', 'wb') as file:
while True:
chunk = await r.content.read(chunk_size)
if not chunk:
break
file.write(chunk)
# List of urls to get images from
urls = [...]
conn = aiohttp.TCPConnector(limit=3)
loop = asyncio.get_event_loop()
session = aiohttp.ClientSession(connector=conn, loop=loop)
loop.run_until_complete(asyncio.gather(*(get_images(url, session=session) for url in urls)))
问题是,我扔了一个打印语句来显示每个请求何时发出,它一次发出近 21 个请求,而不是我想要限制它的 3 个(即,一次图像下载完成后,它可以移动到列表中的下一个 url 获取)。我只是想知道我在这里做错了什么。
【问题讨论】:
标签: python image python-requests python-asyncio aiohttp