From 19a4ec53773448f9797f0ad6b812e0e44dc1eef2 Mon Sep 17 00:00:00 2001 From: inexcode Date: Fri, 28 Oct 2022 11:09:36 +0300 Subject: [PATCH] feat: Add redis pool singleton --- selfprivacy_api/utils/redis_pool.py | 32 +++++++++++++++++++++++++++++ shell.nix | 1 + 2 files changed, 33 insertions(+) create mode 100644 selfprivacy_api/utils/redis_pool.py diff --git a/selfprivacy_api/utils/redis_pool.py b/selfprivacy_api/utils/redis_pool.py new file mode 100644 index 0000000..e4e98ac --- /dev/null +++ b/selfprivacy_api/utils/redis_pool.py @@ -0,0 +1,32 @@ +""" +Redis pool module for selfprivacy_api +""" +import redis.asyncio as redis +from selfprivacy_api.utils.singleton_metaclass import SingletonMetaclass + +REDIS_SOCKET = "/run/redis-sp-api/redis.sock" + + +class RedisPool(metaclass=SingletonMetaclass): + """ + Redis connection pool singleton. + """ + + def __init__(self): + self._pool = redis.ConnectionPool.from_url( + f"unix://{REDIS_SOCKET}", + decode_responses=True, + ) + self._pubsub_connection = self.get_connection() + + def get_connection(self): + """ + Get a connection from the pool. + """ + return redis.Redis(connection_pool=self._pool) + + def get_pubsub(self): + """ + Get a pubsub connection from the pool. + """ + return self._pubsub_connection.pubsub() diff --git a/shell.nix b/shell.nix index 0ccb99d..b6d8e32 100644 --- a/shell.nix +++ b/shell.nix @@ -18,6 +18,7 @@ let black fastapi uvicorn + redis (buildPythonPackage rec { pname = "strawberry-graphql"; version = "0.123.0";