Introduction
Implement caching to improve application performance and reduce database load.
Function Caching
from functools import lru_cache
from datetime import timedelta
@lru_cache(maxsize=128)
def expensive_computation(n):
return n ** 2
# With TTL (time-to-live)
from functools import wraps
import time
def cache_with_ttl(ttl_seconds):
def decorator(func):
cache = {}
@wraps(func)
def wrapper(*args):
now = time.time()
if args in cache:
value, timestamp = cache[args]
if now - timestamp < ttl_seconds:
return value
result = func(*args)
cache[args] = (result, now)
return result
return wrapper
return decorator
Django Caching
# settings.py
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
}
}
# Views
from django.views.decorators.cache import cache_page
@cache_page(60 * 15) # 15 minutes
def my_view(request):
pass
Practice Problems
- Implement function memoization
- Use Redis for application caching
- Cache database queries
- Implement cache invalidation
- Create cache decorator with TTL