I have a django api which returns response like the image path and image location along with city id. I have also added cache_control in the response header to cache the images on the client side. Now I want the api to check the city id after the api is called, if the city id is present as etag in the cache then return the cached response otherwise fetch the new data.
I have tried below code -
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
def calculate_etag_value(request):
return str(city_id)
class MyAPIView(APIView):
def get(self, request):
# Check if the request has an If-None-Match header
if request.META.get('HTTP_IF_NONE_MATCH') == calculate_etag_value(request):
# If the ETag matches, return a 304 Not Modified response
return Response(status=status.HTTP_304_NOT_MODIFIED)
# Generate the response for the GET request
my_data = retrieve_data() # Add your logic to retrieve the data
headers = {
'Cache-Control': 'private, max-age=3600',
'ETag': calculate_etag_value(request),
}
response_data = {
"message": "API info found",
"data": my_data,
}
return Response(response_data, status=status.HTTP_200_OK, headers=headers)
but this is only working if I do hard reload manually, how do I revalidate the city id on the api call as the city id can change anytime so I cannot add the cache_page decorator too? Thanks in Advance!