为什么在使用 aiohttp 模块时必须使用 async with?

hfl*_*qwe 1 python-3.x python-requests python-asyncio aiohttp

当使用编写异步爬虫asyncioaiohttpPython中,我一直有一个疑问:为什么你必须使用async with,并可以很容易地报告错误,如果你不使用它们。

虽然aiohttp也有方法request,但是可以支持调用更简单的api。我想知道有什么区别。还是requests挺喜欢模块的,不知道能不能像requests模块一样简单使用。

use*_*342 5

为什么你必须使用 async with

这不是你必须使用的async with,它只是一个确保资源得到清理的故障安全设备。以文档中的经典示例为例:

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()
Run Code Online (Sandbox Code Playgroud)

您可以将其重写为:

async def fetch(session, url):
    response = await session.get(url)
    return await response.text()
Run Code Online (Sandbox Code Playgroud)

此版本似乎工作相同,但它不会关闭响应对象,因此某些操作系统资源(例如底层连接)可能会继续无限期保留。更正确的版本如下所示:

async def fetch(session, url):
    response = await session.get(url)
    content = await response.text()
    response.close()
    return content
Run Code Online (Sandbox Code Playgroud)

如果在阅读文本时引发异常,此版本仍将无法关闭响应。它可以通过使用固定的finally-这正是withasync with引擎盖下做的。使用async with块,代码更健壮,因为该语言确保在执行离开块时调用清理代码。