core/services/redis.py

82 lines
2.5 KiB
Python
Raw Normal View History

2024-04-08 07:38:58 +00:00
import logging
2024-10-14 10:08:43 +00:00
from redis.asyncio import Redis
2023-12-17 20:30:20 +00:00
2024-11-02 16:16:52 +00:00
from settings import REDIS_URL
2024-01-24 12:36:34 +00:00
2024-02-26 12:56:13 +00:00
# Set redis logging level to suppress DEBUG messages
2024-04-17 15:32:23 +00:00
logger = logging.getLogger("redis")
2024-02-26 12:56:13 +00:00
logger.setLevel(logging.WARNING)
2024-08-07 06:51:09 +00:00
class RedisService:
2023-10-05 18:46:18 +00:00
def __init__(self, uri=REDIS_URL):
self._uri: str = uri
self.pubsub_channels = []
2023-10-13 10:48:17 +00:00
self._client = None
2023-10-05 18:46:18 +00:00
async def connect(self):
2024-11-02 16:16:52 +00:00
if self._uri:
2024-10-14 10:08:43 +00:00
self._client = await Redis.from_url(self._uri, decode_responses=True)
2024-11-02 01:44:07 +00:00
logger.info("Redis connection was established.")
2023-10-05 18:46:18 +00:00
async def disconnect(self):
2024-11-02 01:44:07 +00:00
if isinstance(self._client, Redis):
2023-11-22 16:38:39 +00:00
await self._client.close()
2024-11-02 01:44:07 +00:00
logger.info("Redis connection was closed.")
2023-10-05 18:46:18 +00:00
async def execute(self, command, *args, **kwargs):
2023-11-22 16:38:39 +00:00
if self._client:
try:
2024-06-02 14:01:22 +00:00
logger.debug(f"{command}") # {args[0]}") # {args} {kwargs}")
2024-02-21 13:06:24 +00:00
for arg in args:
if isinstance(arg, dict):
2024-04-17 15:32:23 +00:00
if arg.get("_sa_instance_state"):
del arg["_sa_instance_state"]
2023-11-22 16:38:39 +00:00
r = await self._client.execute_command(command, *args, **kwargs)
2024-06-02 13:14:01 +00:00
# logger.debug(type(r))
# logger.debug(r)
2023-11-22 16:38:39 +00:00
return r
except Exception as e:
2024-01-24 12:36:34 +00:00
logger.error(e)
2023-10-05 18:46:18 +00:00
async def subscribe(self, *channels):
2023-11-22 16:38:39 +00:00
if self._client:
async with self._client.pubsub() as pubsub:
for channel in channels:
await pubsub.subscribe(channel)
self.pubsub_channels.append(channel)
2023-10-05 18:46:18 +00:00
async def unsubscribe(self, *channels):
2023-10-13 10:48:17 +00:00
if not self._client:
2023-10-05 18:46:18 +00:00
return
2023-10-13 10:48:17 +00:00
async with self._client.pubsub() as pubsub:
2023-10-13 10:13:45 +00:00
for channel in channels:
await pubsub.unsubscribe(channel)
self.pubsub_channels.remove(channel)
2023-10-05 18:46:18 +00:00
async def publish(self, channel, data):
2023-10-13 10:48:17 +00:00
if not self._client:
2023-10-05 18:46:18 +00:00
return
2023-10-13 10:48:17 +00:00
await self._client.publish(channel, data)
2023-10-05 18:46:18 +00:00
2024-09-27 07:18:08 +00:00
async def set(self, key, data, ex=None):
# Prepare the command arguments
args = [key, data]
# If an expiration time is provided, add it to the arguments
if ex is not None:
args.append("EX")
args.append(ex)
# Execute the command with the provided arguments
await self.execute("set", *args)
2024-08-08 14:55:34 +00:00
2024-08-08 15:13:51 +00:00
async def get(self, key):
2024-08-08 15:14:49 +00:00
return await self.execute("get", key)
2024-08-08 14:55:34 +00:00
2024-01-25 19:41:27 +00:00
2024-08-07 06:51:09 +00:00
redis = RedisService()
2023-10-05 18:46:18 +00:00
2024-04-17 15:32:23 +00:00
__all__ = ["redis"]