0

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!

Mayank
  • 1
  • 1
  • I'm having a hard time understanding your question. If your city id can change anytime, and you're being forced to do a hard reload, that implies that your 1-hour `max-age` is inappropriate. Perhaps what you want is `no-cache`? That will force the client to consult the API every time but will still allow for conditional validation. – Kevin Christopher Henry Jun 21 '23 at 17:39
  • @KevinChristopherHenry Sorry about the confusion. I want to store the images in the cache and the new data should only be fetched if the etag value (i. e. the city id changes). So, i want the images to be cached always until the city id is changed (my current approach may not be correct) – Mayank Jun 22 '23 at 04:15
  • Right, what you're describing is the behavior of [`no-cache`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#directives): "The `no-cache` response directive indicates that the response can be stored in caches, but the response must be validated with the origin server before each reuse." – Kevin Christopher Henry Jun 22 '23 at 04:24

0 Answers0