fix: Make calls to redis synchronous

This commit is contained in:
Inex Code 2024-12-21 21:04:59 +03:00
parent b609bbc39d
commit 5ca8f43a8e
No known key found for this signature in database

View file

@ -8,21 +8,21 @@ from selfprivacy_api.utils.redis_pool import RedisPool
CACHE_PREFIX = "exec_cache:" CACHE_PREFIX = "exec_cache:"
async def get_redis_object(key: str) -> Optional[Any]: def get_redis_object(key: str) -> Optional[Any]:
redis = RedisPool().get_connection_async() redis = RedisPool().get_connection()
binary_obj = await redis.get(key) binary_obj = redis.get(key)
if binary_obj is None: if binary_obj is None:
return None return None
return pickle.loads(binary_obj) return pickle.loads(binary_obj)
async def save_redis_object(key: str, obj: Any, expire: Optional[int] = 60) -> None: def save_redis_object(key: str, obj: Any, expire: Optional[int] = 60) -> None:
redis = RedisPool().get_connection_async() redis = RedisPool().get_connection()
binary_obj = pickle.dumps(obj) binary_obj = pickle.dumps(obj)
if expire: if expire:
await redis.setex(key, expire, binary_obj) redis.setex(key, expire, binary_obj)
else: else:
await redis.set(key, binary_obj) redis.set(key, binary_obj)
def redis_cached_call(ttl: Optional[int] = 60) -> Callable[..., Callable]: def redis_cached_call(ttl: Optional[int] = 60) -> Callable[..., Callable]:
@ -30,16 +30,13 @@ def redis_cached_call(ttl: Optional[int] = 60) -> Callable[..., Callable]:
@wraps(func) @wraps(func)
async def wrapper(*args, **kwargs) -> Any: async def wrapper(*args, **kwargs) -> Any:
key = f"{CACHE_PREFIX}{func.__name__}:{args}:{kwargs}" key = f"{CACHE_PREFIX}{func.__name__}:{args}:{kwargs}"
cached_value = await get_redis_object(key) cached_value = get_redis_object(key)
if cached_value is not None: if cached_value is not None:
return cached_value return cached_value
if asyncio.iscoroutinefunction(func):
result = await func(*args, **kwargs)
else:
result = func(*args, **kwargs) result = func(*args, **kwargs)
await save_redis_object(key, result, ttl) save_redis_object(key, result, ttl)
return result return result