python / intermediate
Snippet
Django Caching Framework with Per-View Cache
Django's caching framework reduces database load by storing rendered pages or computed data in memory. The @cache_page decorator automatically caches entire view responses based on URL - subsequent requests return cached content. For more control, the low-level cache API lets you manually get/set/delete cache entries with custom keys. Cache backends include local memory (development), Memcached, Redis, and database-backed caching. The cache key should include version numbers when deploying updates to prevent serving stale cached data to users.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# settings.pyCACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache','LOCATION': 'unique-snowflake','OPTIONS': {'MAX_ENTRIES': 1000,'TTL': 60 * 15, # 15 minutes}}}# views.pyfrom django.views.decorators.cache import cache_pagefrom django.core.cache import cache@cache_page(60 * 60) # Cache for 1 hourdef expensive_list_view(request):# Expensive DB queries or computations herereturn render(request, 'expensive.html')# View with cache key based on GET parameters@cache_page(60 * 30, key_prefix='product_list')def product_list(request):category = request.GET.get('category', 'all')products = Product.objects.filter(category=category)return render(request, 'products.html', {'products': products})# Manual cache operationsdef get_homepage_stats():cache_key = 'homepage_stats_v2'stats = cache.get(cache_key)if stats is None:stats = compute_expensive_stats()cache.set(cache_key, stats, timeout=3600)return stats
django
Breakdown
1
@cache_page(60 * 60)
Decorator caches view output for specified seconds (3600 = 1 hour)
2
cache.get(cache_key)
Retrieves value from cache, returns None if key doesn't exist
3
cache.set(cache_key, stats, timeout=3600)
Stores value with optional TTL (time-to-live) in seconds