Registry / database / python-redis-cache

python-redis-cache

JSON →
library4.0.2pypypi✓ verified 87d ago

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-cache
INSTALL
IMPORT
SIG · PYTHON-REDIS-CACHE
P
python-redis-cache
databasepythonv4.0.2
Install
1.9s avg
Import
30ms
Disk
21MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.0.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.032s · 22.6MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 1.9s · import 0.028s · 23MB
21MB installed
● package 21MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

RedisCache
from redis_cache import RedisCache

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).

import os import redis from redis_cache import RedisCache import time # Ensure Redis server is running (e.g., docker run --name some-redis -p 6379:6379 -d redis) # Get Redis connection details from environment variables, or use defaults REDIS_HOST = os.environ.get('REDIS_HOST', 'localhost') REDIS_PORT = int(os.environ.get('REDIS_PORT', '6379')) REDIS_DB = int(os.environ.get('REDIS_DB', '0')) try: # Connect to Redis. decode_responses=True is often useful. redis_client = redis.StrictRedis( host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB, decode_responses=True ) redis_client.ping() # Test connection print(f"Successfully connected to Redis at {REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}") # Initialize RedisCache with the Redis client and a TTL (Time To Live) cache = RedisCache(redis_client=redis_client, ttl=30) # Cache entries for 30 seconds @cache def get_user_data(user_id: int): """Simulates fetching user data from a slow external source.""" print(f"Fetching user {user_id} from original source...") time.sleep(1) # Simulate network delay return {"id": user_id, "name": f"User {user_id}", "fetch_time": time.time()} print("\n--- First call (should fetch from source) ---") user_data1 = get_user_data(101) print(f"User Data 1: {user_data1}") print("\n--- Second call (should be served from cache) ---") user_data2 = get_user_data(101) print(f"User Data 2: {user_data2}") # fetch_time should be the same as user_data1 print("\n--- Third call (different user, fetches from source) ---") user_data3 = get_user_data(102) print(f"User Data 3: {user_data3}") print("\n--- Invalidate cache for user 101 and re-fetch ---") cache.delete_memoized(get_user_data, 101) # Invalidate specific cache entry user_data4 = get_user_data(101) # Should fetch from source again print(f"User Data 4: {user_data4}") except redis.exceptions.ConnectionError as e: print(f"ERROR: Could not connect to Redis at {REDIS_HOST}:{REDIS_PORT}. " "Please ensure Redis server is running. Quickstart cannot proceed.") except Exception as e: print(f"An unexpected error occurred: {e}")
Debug
Known issues
breakingVersion 4.0.0 introduced a breaking change requiring Python 3.8 or newer. It also added support for caching functions with positional-only arguments.
fix
Upgrade your Python environment to 3.8+ if using version 4.0.0 or later.
affects: >=4.0.0
breakingVersion 3.0.0 changed the key format used for storing cached items. This means cached data stored with older versions will not be accessible or compatible with versions 3.0.0 and newer.
fix
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.
affects: >=3.0.0
gotchaProper configuration of the `redis-py` client is crucial. Common issues include incorrect host/port, authentication failures, or not setting `decode_responses=True` if you expect string outputs directly from Redis, which can lead to byte-string issues in your application logic.
fix
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.
affects: All
gotchaCaching class or instance methods requires careful handling. By default, `self` (the instance itself) is part of the cache key, meaning each instance will have its own cache. When invalidating, you must provide the instance to `delete_memoized` if `self` was part of the key.
fix
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.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'redis_cache'
The `python-redis-cache` library is not installed or not available in the current Python environment.
fix
pip install python-redis-cache
TypeError: __init__() missing 1 required positional argument: 'redis_client'
The `RedisCache` class constructor requires an initialized `redis.Redis` client instance as its `redis_client` argument.
fix
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"
AttributeError: 'NoneType' object has no attribute 'get'
The globally imported `cache` decorator (from `from redis_cache import cache`) has not been configured with a `redis_client`, so its internal client remains `None`.
fix
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"
AttributeError: 'RedisCache' object has no attribute 'get'
The `RedisCache` instance is primarily designed as a decorator factory for functions and for cache management operations (like `clear`, `delete`), not for direct key-value `get`/`set` operations like a raw `redis-py` client.
fix
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")
Upgrade
Version history
4.0.2latest on PyPI · released Mar 25, 2025
Audit
Dependencies
redisrequiredRequired for connecting to and interacting with Redis.
Agent activity
9 hits · last 30 days
node
8
Resources
python-redis-cache — pip install python-redis-cache · libregistry