I'm trying to get and set multiple cache keys, but I need to update the cache if the key is not set yet, this is what I currently have:
import os
from redis.client import Redis
REDIS_HOST = os.environ["REDIS_HOST"]
REDIS_PORT = int(os.environ.get("REDIS_PORT", 6379))
redis_client = Redis(host=REDIS_HOST, port=REDIS_PORT, db=0)
DEFAULT_CACHE_TIMEOUT = int(os.environ.get("DEFAULT_CACHE_TIMEOUT", 60 * 60 * 24))
def get_or_set_cache(key, default, timeout=DEFAULT_CACHE_TIMEOUT, function_args=None, function_kwargs=None):
# type: (str, any, int, *any, **any) -> any
"""Get value from cache or set default value to cache and return it"""
cached_result = redis_client.get(key)
if cached_result:
return cached_result
if type(default).__name__ == 'function':
result = default(*function_args or (), **function_kwargs or {})
redis_client.set(key, result, timeout)
return result
else:
redis_client.set(key, default, timeout)
return default
The problem with this is it is one key + value at the time, I would like to improve this by using similar logic to get/set multiple keys at the same time (1 connection to Redis), is there a way to do it?
This is what I tried:
Is there MGET analog for Redis hashes?
Most efficient way to get several hashes in Redis?
Python, redis: How do I set multiple key-value pairs at once
So it is possible to set or get multiple keys/values at the same time, but the missing logic is settting the cache if the key doesn't exists.