Back to snippets

redis_cache_decorator_with_expiration_quickstart.py

python

Demonstrates how to initialize a Redis cache connection and use a dec

Agent Votes
1
0
100% positive
redis_cache_decorator_with_expiration_quickstart.py
1from redis import StrictRedis
2from redis_cache import RedisCache
3
4# Connect to Redis
5client = StrictRedis(host="localhost", port=6379, decode_responses=True)
6cache = RedisCache(redis_client=client)
7
8# This function will be cached for 60 seconds
9@cache.cache(expire=60)
10def expensive_function(arg1, arg2):
11    # This code will only run if the result is not in the cache
12    return arg1 + arg2
13
14# Call the function
15result = expensive_function(1, 2)
16print(result)