from redis import Redis import json class RedisHelper: def get(redis: Redis, key: str) -> any: """Get value from redis as per the key provided. Args: redis: A Redis client object. key: The key to retrieve the value for (string). Returns: The value retrieved from Redis for the given key (can be any type). None if the key doesn't exist. """ value = redis.get(key) if value: # Decode the value if it's a byte string return value.decode("utf-8") if isinstance(value, bytes) else value else: return None def set(redis: Redis, key: str, value: any, ttl=-1): """Set value in redis as per the key-value provided. Args: redis: A Redis client object. key: The key to store the value under (string). value: The value to store (can be any data type). ttl: The time-to-live for the key in seconds (optional, default -1 for no expiry). """ if (ttl > 0): return redis.set(key, value, ex=ttl) return redis.set(key, value) def set_dict(redis: Redis, key: str, value: dict, ttl=-1): """Store a dictionary in Redis as a JSON string. Args: redis: A Redis client object. key: The key to store the dictionary under (string). value: The dictionary to store (dict). ttl: The time-to-live for the key in seconds (optional, default -1 for no expiry). """ # Convert the dictionary to a JSON string before storing value_json = json.dumps(value) # Call the set function with the JSON string if (ttl > 0): return redis.set(key, value_json, ex=ttl) return redis.set(key, value_json)