0
0
Djangoframework~5 mins

Per-view caching in Django

Choose your learning style9 modes available
Introduction

Per-view caching helps your website load faster by saving the result of a page so it doesn't have to be created again each time someone visits.

When you have a page that doesn't change often and is expensive to create.
When you want to reduce the load on your server during busy times.
When you want to speed up response time for users visiting the same page multiple times.
When you want to cache only specific pages instead of the whole site.
Syntax
Django
from django.views.decorators.cache import cache_page

@cache_page(timeout_in_seconds)
def my_view(request):
    # view code here
    return HttpResponse('content')
Use the @cache_page decorator above your view function to enable caching.
The timeout is how long the cached page stays saved before it refreshes.
Examples
This caches the homepage for 15 minutes (60 seconds * 15).
Django
from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def homepage(request):
    return HttpResponse('Welcome to the homepage!')
This caches the about page for 1 hour (3600 seconds).
Django
from django.views.decorators.cache import cache_page

@cache_page(3600)
def about(request):
    return HttpResponse('About us page')
A timeout of 0 means no caching is applied.
Django
from django.views.decorators.cache import cache_page

@cache_page(0)
def no_cache_view(request):
    return HttpResponse('No caching here')
Sample Program

This simple Django view returns a message and caches the page for 30 seconds. If you visit the page multiple times within 30 seconds, Django will serve the saved page instead of running the view again.

Django
from django.http import HttpResponse
from django.views.decorators.cache import cache_page

@cache_page(30)
def hello_view(request):
    return HttpResponse('Hello, this page is cached for 30 seconds!')
OutputSuccess
Important Notes

Remember to import cache_page from django.views.decorators.cache.

Per-view caching works best for pages that do not change for all users.

To clear the cache manually, you may need to restart your server or use cache backend commands.

Summary

Per-view caching saves the output of a view to speed up repeated visits.

Use the @cache_page(timeout) decorator to enable it.

Choose a timeout that fits how often your page content changes.