aiohttp-如何在类名称空间中保存持久会话

时间:2019-03-25 20:45:19

标签: python-3.7 aiohttp

我试图在我的一个项目中使用aiohttp,并且努力找出如何创建持久性aiohttp.ClientSession对象。我已经阅读了aiohttp的官方文档,但在这种情况下没有帮助。

我浏览了其他在线论坛,发现自aiohttp创建以来,发生了许多变化。在github上的一些示例中,显示aiohttp作者正在ClientSession函数(即coroutine)外部创建class Session: def __init__(self): self.session = aiohttp.ClientSession()。我还发现,不应在协程外部创建ClientSession

我尝试了以下方法:

class Session:
    def __init__(self):
        self._session = None

    async def create_session(self):
        self._session = aiohttp.ClientSession()

    async fetch(self, url):
        if self._session is None:
            await self.create_session()
        async with self._session.get(url) as resp:
            return await resp.text()

关于UnclosedSession和连接器,我收到很多警告。我也经常得到SSLError。我还注意到,三个呼叫中有两个被挂起,我必须按CTRL + C杀死它。

使用requests可以简单地在session中初始化__init__对象,但是使用aiohttp并不简单。

如果我使用以下内容(这是我所看到的示例),则看不到任何问题,但是不幸的是,在这里我最终为每个请求创建了ClientSession

def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            return await resp.text()

我可以将aiohttp.ClientSession()包装在另一个函数中,并将其用作上下文管理器,但是每次调用包装函数时,我也最终会创建一个新的session对象。我试图弄清楚如何在类名称空间中保存aiohttp.ClientSession并重用它。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这是工作示例:

from aiohttp import ClientSession, TCPConnector
import asyncio


class CS:

    _cs: ClientSession

    def __init__(self):
        self._cs = ClientSession(connector=TCPConnector(verify_ssl=False))

    async def get(self, url):
        async with self._cs.get(url) as resp:
            return await resp.text()

    async def close(self):
        await self._cs.close()


async def func():
    cs = CS()
    print(await cs.get('https://google.com'))
    await cs.close()  # you must close session


loop = asyncio.get_event_loop()
loop.run_until_complete(func())
相关问题