Welcome back to CodeYourCraft! Today, we're diving into an exciting topic: Per-View Caching in Django. This technique is a powerful tool to optimize your web applications, especially those with heavy traffic or resource-intensive views. Let's get started!
Per-view caching, also known as fragment caching, allows you to cache the output of individual views. This means that you can cache the HTML of a specific page, reducing the time it takes to generate that page when requested again.
To set up per-view caching in Django, we'll use the built-in cache and CacheMiddleware.
Add 'django.middleware.cache.UpdateCacheMiddleware' and 'django.middleware.cache.FetchFromCacheMiddleware' to your MIDDLEWARE setting in settings.py.
MIDDLEWARE = [
...
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
...
]To cache a view, we'll use the cache_page decorator. This decorator takes two arguments: timeout and key_prefix.
from django.views.decorators.cache import cache_page
@cache_page(60 * 60) # Cache for 1 hour
def my_view(request):
...In the above example, my_view will be cached for 1 hour (60 minutes).
You can also cache specific parts of a view using the cache_control decorator. This is useful when you want to cache only a part of a view that doesn't change frequently.
from django.views.decorators.cache import cache_control
def my_view(request):
...
# Cache the 'latest_news' section for 5 minutes
@cache_control(max_age=300)
def latest_news():
...
latest_news()What is Per-View Caching in Django used for?
That's it for today! Stay tuned for more Django tutorials, and remember to practice what you've learned to truly master these concepts. Happy coding! ππ»