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.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.