flask-demo-api/flask_demo_api/repository/redis.py

46 lines
1.2 KiB
Python
Raw Permalink Normal View History

2024-04-16 01:03:02 +03:00
import pickle
2024-04-15 04:02:47 +03:00
import redis # type: ignore
2024-04-16 01:03:02 +03:00
from flask_demo_api.protocols.models import KeyDTO
from flask_demo_api.protocols.repository import Repository
2024-04-15 02:16:07 +03:00
class RedisRepository(Repository):
def __init__(self, redis_pool: redis.Redis) -> None:
self.pool = redis_pool
2024-04-16 04:48:10 +03:00
def __set(self, key, val):
data = pickle.dumps(val)
self.pool.set(key, data)
def __get(self, key):
data = self.pool.get(key)
if data is not None:
return pickle.loads(data)
return None
2024-04-15 02:16:07 +03:00
def get_key(self, obj: KeyDTO) -> KeyDTO | None:
2024-04-16 04:48:10 +03:00
data = self.__get(obj.key)
2024-04-16 01:03:02 +03:00
if not data:
return None
2024-04-16 04:48:10 +03:00
return KeyDTO(key=obj.key, val=data)
2024-04-15 02:16:07 +03:00
2024-04-16 04:48:10 +03:00
def add_key(self, obj: KeyDTO) -> KeyDTO | None:
data = self.__get(obj.key)
if data:
return None
self.__set(obj.key, obj.val)
2024-04-16 01:03:02 +03:00
return obj
2024-04-15 02:16:07 +03:00
2024-04-16 04:48:10 +03:00
def put_key(self, obj: KeyDTO) -> KeyDTO | None:
data = self.__get(obj.key)
if data is None:
return None
self.__set(obj.key, obj.val)
return obj
2024-04-16 01:03:02 +03:00
def delete_key(self, obj: KeyDTO) -> None:
2024-04-16 04:48:10 +03:00
self.pool.delete(obj.key)
2024-04-16 01:03:02 +03:00
return None