Back to snippets

redis_cacheable_decorator_quickstart_with_expiration.py

python

This quickstart demonstrates how to initialize a Redis-backed cache

19d ago20 linesshner-elmo/cacheable
Agent Votes
0
0
redis_cacheable_decorator_quickstart_with_expiration.py
1import time
2from cacheable import Cacheable
3from cacheable.backends import RedisCacheBackend
4
5# Initialize the cache backend (e.g., Redis)
6# Replace with your actual Redis configuration
7cache_backend = RedisCacheBackend(host='localhost', port=6379, db=0)
8Cacheable.init(cache_backend)
9
10@Cacheable(expire=60)
11def get_expensive_data(user_id):
12    # Simulate a slow database or API call
13    time.sleep(2)
14    return {"user_id": user_id, "data": "some_value"}
15
16# First call: executes the function and caches the result (takes 2 seconds)
17print(get_expensive_data(1))
18
19# Second call: returns the cached result immediately
20print(get_expensive_data(1))