简体   繁体   中英

Cache doesn't work for django restframwork POST API

I have cache settings in settings.py

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': 'django_cache',
    }
}

in view.py

from django.views.decorators.cache import cache_page
from rest_framework.response import Response

@cache_page(60*15)
@api_view(['POST', 'GET'])
def get_route(request):
    res = {}
    # some calculation.
    return Response(res)

post with this json

{ 
"ids_item":[4,1,2,3],
"id":10
}   

At first access, cache file is made under django_cache directory, (OK it's cool and smooth.)

However second access with same json, it calculates again and makes another cache file.

I want to use cache when the json is the same.

How can I make this??

From the documentation of the django source code:

Only GET or HEAD-requests with status code 200 are cached.

https://github.com/django/django/blob/main/django/middleware/cache.py#:~:text=Only%20GET%20or%20HEAD%2Drequests%20with%20status%20code%20200%20are%20cached.

If your post request is taking too much time to process the request, may be you can try out the below method.

1.  get the post json ({ "ids_item":[4,1,2,3],"id":10})

2.  save the response for that request to cache using the id (10) 

3.  On next post request, check if item with id 10 in cache exists

4.  if not save it to cache, else return the value from cache

It can be done like :

from django.core.cache import cache

id_from_request=10 # get it from the input json or use any unique identifier
obj=cache.get(id_from_request)
if not obj:
    obj= response you are returning for that input json
    cache.set(id_from_request, obj, 900) #save the response for 15 min in cache
else:
    return obj #change this to json or http response

You can create a hash of file content as key and value as file object something like this:

import hashlib, json

def get_route(request):
     res = {}
     res = json.dumps(res, sort_keys = True).encode("utf-8")
     hash = hashlib.md5(res).hexdigest()
     file = cache.get(hash)
     if not file:
         file = # some calculation
         cache.set(hash, file, your_time_out)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM