Кэш не работает для API POST от django restframwork

У меня есть настройки кэша в settings.py

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

в 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)

разместите с помощью этого json

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

При первом доступе, файл кэша создается в каталоге django_cache, (OK это круто и гладко.)

При втором обращении с тем же json, он снова вычисляет и создает другой кэш-файл.

Я хочу использовать кэш, когда json одинаковый.

Как я могу это сделать?

Из документации к исходному коду django :

Кэшируются только GET или HEAD-запросы с кодом состояния 200.

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

Если ваш почтовый запрос занимает слишком много времени для обработки запроса, возможно, вы можете попробовать следующий метод.

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

Это можно сделать так:

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

Вы можете создать хэш с содержимым файла в качестве ключа и значением в качестве объекта файла примерно так:

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)
Вернуться на верх