From 4b9b47feb83f8001d8500a06cf10a49cdb815e7f Mon Sep 17 00:00:00 2001 From: Charles P Date: Tue, 14 Nov 2023 21:44:08 +0100 Subject: [PATCH] :zap: perf: use persistant aiohttp session --- plugins/monitoring/monitoring.py | 40 +++++++++++++++----------------- requirements.txt | 6 ++--- 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/plugins/monitoring/monitoring.py b/plugins/monitoring/monitoring.py index c69f7bb3..6ef5cc4a 100644 --- a/plugins/monitoring/monitoring.py +++ b/plugins/monitoring/monitoring.py @@ -6,13 +6,11 @@ """ import time -# pylint: disable=unused-import -from discord.ext import tasks, commands - import aiohttp +from discord.ext import tasks, commands -from utils import Gunibot, MyContext import core +from utils import Gunibot async def setup(bot: Gunibot = None): @@ -26,6 +24,7 @@ def __init__(self, bot: Gunibot): self.logger = core.setup_logger(self.file) self.config = core.config.get(self.file) self.error_counter = 0 + self.session = aiohttp.ClientSession() async def cog_load(self) -> None: if self.config["monitoring_enabled"]: @@ -33,7 +32,7 @@ async def cog_load(self) -> None: if await self.ping_monitoring(): self.logger.info("Monitoring test ping successful") self.logger.info("Monitoring enabled") - self.loop.start() + self.loop.start() #pylint: disable=no-member return else: self.logger.warning("Monitoring ping failed %s times", i + 1) @@ -50,22 +49,21 @@ async def ping_monitoring(self): "?status=up&msg=OK&ping=" + str(ping)) # send request - async with aiohttp.ClientSession() as session: - async with session.get(url) as resp: - if resp.status != 200: - self.logger.error("Monitoring ping failed with status %s", resp.status) - return False - else: - json = await resp.json() - try: - if not json["ok"]: - self.logger.error("Monitoring ping failed with error : %s", json["msg"]) - return False - else: - return True - except KeyError: - self.logger.error("Monitoring ping failed") + async with self.session.get(url) as resp: + if resp.status != 200: + self.logger.error("Monitoring ping failed with status %s", resp.status) + return False + else: + json = await resp.json() + try: + if not json["ok"]: + self.logger.error("Monitoring ping failed with error : %s", json["msg"]) return False + else: + return True + except KeyError: + self.logger.error("Monitoring ping failed") + return False @tasks.loop(seconds=20) async def loop(self): @@ -75,7 +73,7 @@ async def loop(self): self.error_counter += 1 if self.error_counter >= 6: self.logger.error("Monitoring disabled due to multiple ping failure") - self.loop.stop() + self.loop.stop() #pylint: disable=no-member @loop.before_loop async def before_ping_monitoring(self): diff --git a/requirements.txt b/requirements.txt index 96a6b9d3..74a558a6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,8 +1,8 @@ -psutil -aiohttp +psutil~=5.9.5 +aiohttp~=3.8.5 gitpython >= 3.1.8 python-i18n -pyyaml +pyyaml~=6.0.1 emoji >= 2.0 feedparser >= 6.0 async-timeout >= 3.0