【问题标题】:Why do I have to use async with when using the aiohttp module?为什么我在使用 aiohttp 模块时必须使用 async with?
【发布时间】:2019-03-19 05:28:11
【问题描述】:

在Python中使用asyncioaiohttp编写异步爬虫时,一直有一个疑问:为什么一定要使用async with,不使用很容易报错。

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

【问题讨论】:

    标签: python-3.x python-requests python-asyncio aiohttp


    【解决方案1】:

    为什么你必须使用async with

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

    async def fetch(session, url):
        async with session.get(url) as response:
            return await response.text()
    

    你可以重写为:

    async def fetch(session, url):
        response = await session.get(url)
        return await response.text()
    

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

    async def fetch(session, url):
        response = await session.get(url)
        content = await response.text()
        response.close()
        return content
    

    如果在阅读文本时引发异常,此版本仍然无法关闭响应。它可以通过使用finally 来修复——这正是withasync with 在幕后所做的。使用async with 块,代码更加健壮,因为该语言确保在执行离开块时调用清理代码。

    【讨论】:

    • 想你的答案。但我还有一个问题,我想知道为什么异步很重要。
    • @hfldqwe 答案在最后一段中解决了这个问题。如果有不清楚的地方,请具体说明,以便我改进。
    • 很抱歉现在回复,我有一个看不懂的地方:我在文档(和许多其他解释)中强调了我想使用异步,但它不是允许使用它。而且async with有个问题(就是session没有关闭),不知道Python的对象回收机制能不能处理。如果我在我的项目中使用aiohttp作为爬虫,使用tornado编写后端接口,那么在Tornado的RequestHandler中写async with似乎是非常困难的。
    • 通常我会这样做。 ``` Async def login(self, client, username, password'): ... Async with client.post(url.login_url(), headers=url.headers, data=data) as resp: Result = await resp. json() # 判断是否登录成功 If result['success'] == True: Return resp.cookies ``` ``` Async with aiohttp.ClientSession(cookie_jar=jar) as client: Cookies = await spider.login (客户端,用户名=用户名,密码=密码)```
    • 但在龙卷风中我无法将客户端作为参数传递给我的爬虫。 eg: ``` Class InfoHandler(BaseHandler): ''' 返回个人信息 ''' Async def get(self): Async with aiohttp.ClientSession() as client: Result = await spider.login(client,username=' xxx', password='xxx') ``` 这样会为每个链接创建一个session,比较浪费资源,不建议在aiohttp中使用。我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2013-04-30
    相关资源
    最近更新 更多