python-redis-cache is a Python library providing a simple decorator for Redis-based caching of function results. It integrates with `redis-py` to store and retrieve data, offering features like TTL (Time To Live) and cache limits. The library is actively maintained, with frequent releases addressing bug fixes, new features, and occasional breaking changes to improve functionality.
pip install python-redis-cacheVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to initialize `RedisCache` with a `redis-py` client and use the `@cache` decorator on a function. It shows how the cache stores results for subsequent calls with the same arguments, and how to manually invalidate a specific cache entry. Ensure a Redis server is accessible at the specified host and port (or defaults).
Upgrade your Python environment to 3.8+ if using version 4.0.0 or later.
When upgrading from a version older than 3.0.0, consider flushing your Redis cache if you rely on existing cached data, as it will become inaccessible. New data will be stored in the new format.
Always test your `redis.StrictRedis` or `redis.Redis` connection independently (e.g., with `client.ping()`) before passing it to `RedisCache`. Pay attention to `host`, `port`, `db`, `password`, and `decode_responses` parameters.
Be explicit about how `self` affects your cache keys. If you want a class method to be cached globally regardless of instance, you might need to adjust key generation or consider caching outside the method. For instance methods, use `cache.delete_memoized(YourClass.method, obj_instance=your_instance)` for invalidation.
pip install python-redis-cache
import redis
from redis_cache import RedisCache
redis_client = redis.Redis(host='localhost', port=6379, db=0)
cache = RedisCache(redis_client=redis_client)
@cache.cache()
def my_function():
return "cached data"import redis
from redis_cache import cache
# Configure the globally imported cache instance with a Redis client
cache.redis_client = redis.Redis(host='localhost', port=6379, db=0)
@cache.cache()
def my_function():
return "cached data"import redis
from redis_cache import RedisCache
redis_client = redis.Redis(host='localhost', port=6379, db=0)
cache = RedisCache(redis_client=redis_client)
# To use the cache for a function:
@cache.cache(ttl=60)
def get_user_data(user_id):
# ... fetch from DB ...
return {"id": user_id, "name": f"User {user_id}"}
user_data = get_user_data(1) # This retrieves from cache if available
# For direct Redis key operations, use the underlying redis_client instance:
redis_client.set("my_key", "my_value")
value = redis_client.get("my_key")