Aiohttp - 在轮询 restful api 时,我应该让会话保持 24/7 活动吗?

Aiohttp - should I keep the session alive 24/7 when polling restful api?

抱歉,这里是图书馆新手。我每 10 秒轮询一个 restful 端点。 以下哪项是合适的对我来说并不明显:

import aiohttp
import asyncio

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

async def main():
    while True:
        await asyncio.sleep(10)
        print(await poll('http://example.com/api'))

loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()

或者会话变量永远存在:

import aiohttp
import asyncio

async def poll(url):
    async with aiohttp.ClientSession() as session:
        await asyncio.sleep(10)
        async with session.get(url) as r:
            print(await r.text())

loop = asyncio.get_event_loop()
loop.create_task(poll('http://example.com/api'))
loop.run_forever()

我希望后者是可取的,但来自非异步请求库,我不习惯会话的想法。我真的会因为连接池或其他原因而体验到更快的响应时间吗?

来自官方文档:

Don’t create a session per request. Most likely you need a session per application which performs all requests altogether.

A session contains a connection pool inside. Connection reusage and keep-alives (both are on by default) may speed up total performance.

当然是后者更好,肯定你会有更快的体验。