File tree Expand file tree Collapse file tree 2 files changed +24
-1
lines changed Expand file tree Collapse file tree 2 files changed +24
-1
lines changed Original file line number Diff line number Diff line change 11from django .urls import path
22
3- from .views import view_products
3+ from .views import view_products , view_cached_products
44
55app_name = 'store'
66
77urlpatterns = [
88path ('' , view_products , name = 'products' ),
9+ path ('cache/' , view_cached_products , name = 'cached-products' ),
910]
Original file line number Diff line number Diff line change 11from django .shortcuts import render
2+ from django .core .cache import cache
3+ from django .conf import settings
4+ from django .core .cache .backends .base import DEFAULT_TIMEOUT
25
36from rest_framework .decorators import api_view
47from rest_framework .response import Response
58from rest_framework import status
69
710from .models import Product
811
12+ CACHE_TTL = getattr (settings , 'CACHE_TTL' , DEFAULT_TIMEOUT )
13+
914@api_view (['GET' ])
1015def view_products (request ):
1116products = Product .objects .all ()
1217results = [product .to_json () for product in products ]
1318return Response (data = results , status = status .HTTP_201_CREATED )
19+
20+
21+ # view for cached products
22+ @api_view (['GET' ])
23+ def view_cached_products (request ):
24+ if 'product' in cache :
25+ print ("True" )
26+ products = cache .get ('product' )
27+ return Response (data = products , status = status .HTTP_201_CREATED )
28+ else :
29+ print ("False" )
30+ products = Product .objects .all ()
31+ results = [product .to_json () for product in products ]
32+
33+ # store products in cache
34+ cache .set (products , results , timeout = CACHE_TTL )
35+ return Response (data = results , status = status .HTTP_201_CREATED )
You can’t perform that action at this time.
0 commit comments