Low-Level Cache API Example
A snippet showing how to use DjangoÆs low-level cache API.
# views.py
from django.core.cache import cache
from django.http import JsonResponse
def stats_view(request):
stats = cache.get("site_stats")
if stats is None:
# expensive operation
stats = {"users": 1200, "orders": 345}
cache.set("site_stats", stats, timeout=300) # 5 minutes
return JsonResponse(stats)
Explanation:
-
Use
cache.get_or_set(key, default, timeout=...)to simplify the pattern. - First request computes and stores data; later requests are served from cache until timeout.
- Category Performance & Optimization
- Total Views 352
- Last Modified 16 April, 2026
- Tags #performance #caching #low-level #redis
Previous snippet
Using cache_page Decorator
Next snippet