osnova-api-alert/redis_db/r_helper.py

32 lines
903 B
Python
Raw Normal View History

2024-10-08 19:29:50 +00:00
from redis.asyncio import Redis
2024-10-08 21:14:07 +00:00
from redis import ConnectionError
2024-10-08 19:29:50 +00:00
from config import conf
import logging as log
2024-10-08 21:14:07 +00:00
class RedisManager:
def __init__(self):
self.client = None
self.connect_params = {
"host": conf.redis.host,
"port": conf.redis.port,
}
if conf.redis.pwd:
self.connect_params["password"] = conf.redis.pwd
2024-10-08 19:29:50 +00:00
async def __aenter__(self):
2024-10-08 21:14:07 +00:00
self.client = Redis(**self.connect_params)
try:
2024-10-09 08:28:57 +00:00
await self.client.ping()
2024-10-08 21:14:07 +00:00
log.info("connected to Redis")
return self
except ConnectionError:
log.warning("failed to connect to Redis")
self.client = None
2024-10-09 08:28:57 +00:00
return None
2024-10-08 19:29:50 +00:00
2024-10-08 21:14:07 +00:00
async def __aexit__(self, exc_type, exc_val, exc_tb):
if self.client:
await self.client.close()
log.info("closed connection to Redis")