0
0
Djangoframework~30 mins

Cache invalidation strategies in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Cache Invalidation Strategies in Django
📖 Scenario: You are building a Django web application that shows a list of products. To improve performance, you want to cache the product list page. However, when products change, the cache must be invalidated so users see fresh data.
🎯 Goal: Build a simple Django view that caches the product list page and invalidates the cache when a product is updated.
📋 What You'll Learn
Create a dictionary called products with three products and their prices.
Create a variable called cache_timeout and set it to 300 seconds.
Write a Django view function called product_list that caches the product list page using cache.get and cache.set.
Add a function called invalidate_cache that deletes the cached product list when a product is updated.
💡 Why This Matters
🌍 Real World
Caching is used in web apps to speed up page loading by storing data temporarily. Cache invalidation ensures users see updated information after changes.
💼 Career
Understanding cache invalidation is important for backend developers working with Django or any web framework to build fast and reliable applications.
Progress0 / 4 steps
1
Create the initial product data
Create a dictionary called products with these exact entries: 'apple': 1.2, 'banana': 0.5, 'cherry': 2.5.
Django
Need a hint?

Use curly braces to create a dictionary with the exact keys and values.

2
Set the cache timeout duration
Create a variable called cache_timeout and set it to 300 (seconds).
Django
Need a hint?

Just assign the number 300 to the variable cache_timeout.

3
Create the cached product list view
Write a Django view function called product_list that uses cache.get('product_list') to get cached data. If cache is empty, create a string listing products and prices, then store it with cache.set('product_list', product_data, cache_timeout). Return the product data string.
Django
Need a hint?

Use cache.get to check cache, build the string if missing, then use cache.set to save it.

4
Add cache invalidation function
Add a function called invalidate_cache that calls cache.delete('product_list') to remove the cached product list when a product is updated.
Django
Need a hint?

Use cache.delete with the same cache key to remove cached data.