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.

Easy Python 3.9+ Aug 9, 2026 Caching & Redis 11 views 0 copies

Requires third-party packages — install first
pip install redis

Python code

44 lines
Python 3.9+
import 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

stdout
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

  1. Use `setex` with a `timedelta` for more precise TTL control
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Caching & Redis

Related tutorials and quizzes for this topic.