I am using drf-extension for caching my APIs. But it is not working as expected with cache_response decorator.
It caches the response for say /api/get-cities/?country=india
. But when I hit /api/get-cities/?country=usa
, I get the same response.
Here is the sample code:
settings.py
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient"
},
"KEY_PREFIX": "city"
}
}
REST_FRAMEWORK_EXTENSIONS = {
'DEFAULT_USE_CACHE': 'default',
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 86400,
}
views.py
class GetCities(APIView):
@cache_response()
def get(self, request):
country = request.GET.get("country", "")
return get_cities_function(country)
Please help with this.
I was able to find a solution for the problem. I created my own keys in redis with the combination of api name and parameter name(in my case country). So when API is hit with query parameters, I check if a key exists corresponding to that, if it exists then cached response is returned.
class GetCities(APIView):
def calculate_cache_key(self, view_instance, view_method, request, args, kwargs):
api = view_instance.get_view_name().replace(' ', '')
return "api:" + api + "country:" + str(request.GET.get("country", ""))
@cache_response(key_func='calculate_cache_key')
def get(self, request):
country = request.GET.get("country", "")
return get_cities_function(country)