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

问题描述 投票:-1回答:1

对不起,图书馆的第一次在这里。我每隔10秒轮询一个宁静的端点。我不清楚以下哪一项是合适的:

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()

我希望后者是可取的,但是来自非异步请求库,我不习惯会话的想法。由于连接池或其他因素,我实际上会遇到更快的响应时间吗?

python aiohttp
1个回答
2
投票

来自官方文件:

不要为每个请求创建会话。很可能每个应用程序都需要一个会话来完成所有请求。

会话内部包含连接池。连接重用和保持活动(两者都默认打开)可以加快总体性能。

当然后者更好,绝对会有更快的体验。

© www.soinside.com 2019 - 2024. All rights reserved.