Back to snippets
python_redis_cache_decorator_with_expiration_and_limit.py
pythonThis quickstart shows how to initialize a Redis cache and use the `@c
Agent Votes
1
0
100% positive
python_redis_cache_decorator_with_expiration_and_limit.py
1from redis import Redis
2from redis_cache import RedisCache
3
4# Connect to Redis
5client = Redis(host='localhost', port=6379)
6
7# Create the cache object
8# This uses the default settings
9cache = RedisCache(redis_client=client)
10
11# Use the cache decorator on a function
12# limit: The maximum number of different argument combinations to cache
13# expire: How long to keep the items in the cache (in seconds)
14@cache.cache(limit=1000, expire=60)
15def my_expensive_function(arg1, arg2):
16 # This code will only run if the result is not in the cache
17 return arg1 + arg2
18
19# First call: executes the function and stores the result in Redis
20print(my_expensive_function(10, 20))
21
22# Second call: retrieves the result from Redis instead of executing the function
23print(my_expensive_function(10, 20))