From 6df509863d0ec2684e7c2cc13b27686aa87cffb6 Mon Sep 17 00:00:00 2001 From: Bradley Wells Date: Fri, 22 Mar 2024 20:33:00 +0200 Subject: [PATCH] Add @api_view example to caching documentation (#9131) --- docs/api-guide/caching.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/api-guide/caching.md b/docs/api-guide/caching.md index 503acb09e..d5f7ecb3a 100644 --- a/docs/api-guide/caching.md +++ b/docs/api-guide/caching.md @@ -59,6 +59,31 @@ class PostView(APIView): return Response(content) ``` + +## Using cache with @api_view decorator + +When using @api_view decorator, the Django-provided method-based cache decorators such as [`cache_page`][page], +[`vary_on_cookie`][cookie] and [`vary_on_headers`][headers] can be called directly. + +```python +from django.views.decorators.cache import cache_page +from django.views.decorators.vary import vary_on_cookie + +from rest_framework.decorators import api_view +from rest_framework.response import Response + + +@cache_page(60 * 15) +@vary_on_cookie +@api_view(['GET']) +def get_user_list(request): + content = { + 'user_feed': request.user.get_user_feed() + } + return Response(content) +``` + + **NOTE:** The [`cache_page`][page] decorator only caches the `GET` and `HEAD` responses with status 200.