selfprivacy-rest-api/selfprivacy_api/utils/cached_call.py

46 lines
1.2 KiB
Python
Raw Normal View History

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