How to Use Redis as a Cache in Python
A beginner-friendly RedisCache helper that stores, retrieves, and deletes JSON values with automatic TTL expiration using the redis-py client.
pip install redis
Python code
44 linesimport json
import time
import redis
class RedisCache:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.default_ttl = default_ttl
def set(self, key, value, ttl=None):
"""Store a value with optional TTL (seconds)."""
ttl = ttl or self.default_ttl
data = json.dumps(value)
self.client.setex(key, ttl, data)
def get(self, key):
"""Retrieve a value, returning None if missing or expired."""
data = self.client.get(key)
if data is None:
return None
return json.loads(data)
def delete(self, key):
"""Remove a key from cache."""
self.client.delete(key)
def exists(self, key):
"""Check if a key exists."""
return self.client.exists(key) > 0
if __name__ == "__main__":
cache = RedisCache(default_ttl=5)
# Store and retrieve a simple value
cache.set("greeting", {"message": "Hello world", "timestamp": time.time()})
result = cache.get("greeting")
print(f"Cached data: {result}")
# Verify existence and quick cleanup
print(f"Exists before delete: {cache.exists('greeting')}")
cache.delete("greeting")
print(f"Exists after delete: {cache.exists('greeting')}")
Output
Cached data: {'message': 'Hello world', 'timestamp': 1712345678.123456}
Exists before delete: True
Exists after delete: False
How it works
The RedisCache class wraps redis.Redis with decode_responses=True so keys and values are returned as strings instead of bytes. setex assigns a TTL at write time, so expired keys are automatically removed by Redis. json.dumps serializes dicts and lists into strings for storage, and json.loads restores them on read, giving you native Python objects. The default_ttl parameter lets you set a fallback expiry for keys that don't specify their own, which keeps cache memory bounded.
Common mistakes
- Forgetting `decode_responses=True`, which returns bytes and breaks JSON decoding
- Passing `None` as a TTL thinking it disables expiry — it falls back to the default TTL
- Storing non-JSON-serializable objects like datetimes without converting them first
- Not handling redis connection errors when Redis is down
Variations
- Use `setex` with a `timedelta` for more precise TTL control
- Add a `get_or_set` method that computes and caches a value on cache miss
Real-world use cases
- Caching database query results so repeated reads don't hit the database.
- Storing API responses with a short TTL to reduce upstream API call load.
- Caching session tokens or user preferences in a shared cache across multiple application instances.
Sponsored
More from Caching & Redis
- Cache Asides in Python with a Read-Through Loader easy
- Cache Data in Redis with Python easy
- Cache Penetration Null Object Mock in Python medium
- Cache Stampede Prevention with SingleFlight in Python medium
- Cache Warming with Python: Preload Hot Keys easy
- Coalescing duplicate in-flight requests: one shared result for concurrent callers hard
Keep learning
Related tutorials and quizzes for this topic.