如何关闭 aiohttp ClientSession

G0r*_*0rt 7 python aiohttp

我正在尝试制作一个可以存活一天、一周或更长时间的应用程序。在应用程序的生命周期中,它会向不同的 API 发出请求。其中一些 api 可能需要登录,因此我可以随时访问 cookie,这一点很重要。

所以我需要的是一个不同的 API 可以在不阻塞应用程序的情况下使用的文件。

我是异步编程(asyncio/aiohttp)的新手,我见过的示例展示了如何从 url 列表发出大量请求,但这不是我需要的。

我的代码的问题是,我得到 ClientSession is closed 错误或未关闭的 ClientSession 警告。

import asyncio  # only here for debugging purposes
import aiohttp

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:61.0) Gecko/20100101 Firefox/61.1'


def default_headers():
    header = {
        'User-Agent': USER_AGENT
    }
    return header


class WebSession(object):
    session = None

    @classmethod
    def create(cls):
        cls.session = aiohttp.ClientSession()
        return cls.session

    @classmethod
    def close(cls):
        if cls.session is not None:
            cls.session.close()

async def request(method, url, **kwargs):

    if kwargs.get('headers', None) is None:
        kwargs['headers'] = default_headers()

    if WebSession.session is None:
        session = WebSession.create()
    else:
        session = WebSession.session


    async with session.request(method=method, url=url, **kwargs) as response:
        if isinstance(session, aiohttp.ClientSession):
            # if i close the session here, i will get the ClientSession closed error on 2. request.
            # await session.close()
            pass

        return response


async def get(url, **kwargs):
    return await request('GET', url=url, **kwargs)


async def post(url, **kwargs):
    return await request('POST', url=url, **kwargs)


async def get_url():
    res = await get('https://httpbin.org/get')
    print(f'Status code: {res.headers}')


m_loop = asyncio.get_event_loop()
m_loop.run_until_complete(get_url())
# if i run this without closing the ClientSession, i will get unclosed ClientSession warnings.
m_loop.run_until_complete(get_url())
m_loop.close()
Run Code Online (Sandbox Code Playgroud)

我确实收到了服务器的响应,但随后是此错误/警告

Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x03354630>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at   0x033BBBF0>, 71.542)]']
connector: <aiohttp.connector.TCPConnector object at 0x033542D0>
Run Code Online (Sandbox Code Playgroud)

如果我取消注释await session.close()并删除pass我在第一个请求中从服务器收到响应,然后RuntimeError: Session is closed在第二个请求中。

G0r*_*0rt 9

啊,我想我现在明白了。

我得到了警告Unclosed client session,并Unclosed connector为aiohttp告诉我:“嘿,你忘了关闭会话”。这正是这个小例子发生的事情。两次调用get_url实际上都会从服务器获得响应,然后应用程序将结束。因此,当应用程序结束时,会话将处于未关闭状态,这就是显示上述警告的原因。

我不应该在每次请求后关闭会话,因为那时无法发出新请求,至少我不知道。这就是为什么我RuntimeError: Session is closed在尝试提出新请求时得到的原因,一旦它已经关闭。

所以一旦我想通了这一点,我就创建了一个关闭函数,并在循环(应用程序)结束之前简单地调用它。现在我没有收到警告/错误。现在,在应用程序运行时,所有请求(我认为)之间都会共享 cookie。无论它们是 GET 还是 POST,这正是我想要的。

我希望其他不熟悉 aiohttp/asyncio 的人会从中受益,因为我花了一些时间(太长)来理解。由于我还是 aiohttp/asyncio 的新手,我不知道这是否是正确的做法,但至少它似乎有效。

import asyncio  # only here for debugging purposes
import aiohttp

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:61.0) Gecko/20100101 Firefox/61.1'


def default_headers():
    header = {
        'User-Agent': USER_AGENT
    }
    return header


class WebSession(object):
    session = None

    @classmethod
    def create(cls):
        cls.session = aiohttp.ClientSession()
        return cls.session

    @classmethod
    def close(cls):
        if cls.session is not None:
            # apparently this is supposed to return a future?
            return cls.session.close()


async def request(method, url, **kwargs):

    if kwargs.get('headers', None) is None:
        kwargs['headers'] = default_headers()

    if WebSession.session is None:
        session = WebSession.create()
    else:
        session = WebSession.session

    return await session.request(method=method, url=url, **kwargs)


async def get(url, **kwargs):
    return await request('GET', url=url, **kwargs)


async def post(url, **kwargs):
    return await request('POST', url=url, **kwargs)


async def get_url():
    res = await get('https://httpbin.org/get')
    print(f'Headers: {res.headers}')


async def close():
    # run this before the app ends
    await WebSession.close()

# so imagine that this is our app.
m_loop = asyncio.get_event_loop()
# its running now and doing stuff..

# then it makes a request to a url.
m_loop.run_until_complete(get_url())
# then some time passes, and then it makes another request to a url.
m_loop.run_until_complete(get_url())
# now the app gets stopped, whether by keyboard interrupt or some other means of stopping it
# then close the session
m_loop.run_until_complete(close())
# and then end the app..
m_loop.close()
Run Code Online (Sandbox Code Playgroud)