aiohttp中request.iter_content()的等价方法是什么?
What is the equivalent method of request.iter_content() in aiohttp?
我正在编写一个小型网络抓取工具,它可以从特定站点获取大量图像。然而,IO 速度很慢,所以我用谷歌搜索并找到了 asyncio 和 aiohttp 来处理 IO 绑定操作开销。我梳理了 aiohttp 文档,但在请求模块中找不到任何看起来可以替代 iter_content() 的函数。我需要它将图像数据写入磁盘。有人可以帮忙吗?
您应该使用 ClientResponse.content
属性。这是一个 StreamReader
实例,可用于增量读取响应。来自 docs:
with open(filename, 'wb') as fd:
while True:
chunk = await r.content.read(chunk_size)
if not chunk:
break
fd.write(chunk)
StreamReader
也支持异步迭代:
async for line in r.content:
...
async for chunk in r.content.iter_chunked(1024):
...
async for slice in r.content.iter_any(): # as much as possible before blocking
...
我正在编写一个小型网络抓取工具,它可以从特定站点获取大量图像。然而,IO 速度很慢,所以我用谷歌搜索并找到了 asyncio 和 aiohttp 来处理 IO 绑定操作开销。我梳理了 aiohttp 文档,但在请求模块中找不到任何看起来可以替代 iter_content() 的函数。我需要它将图像数据写入磁盘。有人可以帮忙吗?
您应该使用 ClientResponse.content
属性。这是一个 StreamReader
实例,可用于增量读取响应。来自 docs:
with open(filename, 'wb') as fd:
while True:
chunk = await r.content.read(chunk_size)
if not chunk:
break
fd.write(chunk)
StreamReader
也支持异步迭代:
async for line in r.content:
...
async for chunk in r.content.iter_chunked(1024):
...
async for slice in r.content.iter_any(): # as much as possible before blocking
...