这是一个小代码片段:
import aiohttp
import aiofiles
async def fetch(url):
# starting a session
async with aiohttp.ClientSession() as session:
# starting a get request
async with session.get(url) as response:
# getting response content
content = await response.content
return content
async def save_file(file_name, content):
async with aiofiles.open(f'./binary/{file_name}', 'wb') as f:
while True:
chunk = content.read(1024)
if not chunk:
break
f.write(chunk)
我正在尝试使用库下载一些二进制文件aiohttp
,然后使用库将它们传递给协程aiofiles
以将文件写入磁盘。我已经阅读了文档,但仍然无法确定我是否可以通过content = await response.content
,或者当手柄关闭时它async with..
是否关闭?因为在二级博客上,我发现:
根据 aiohttp 的文档,因为响应对象是在上下文管理器中创建的,所以它在技术上隐式调用 release()。
这让我感到困惑,我应该将第二个函数的逻辑嵌入到response
句柄中还是我的逻辑正确?