File size: 1,889 Bytes
ef1ad9e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
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)
|