I have a Django (1.8.17) app, and I am using Tastypie (0.13.3) as REST API Framework.
I have some very simple resources, and I use SimpleCache
to cache them for 15 minutes.
from tastypie.resources import ModelResource
from my_app.models import MyModel
from tastypie.cache import SimpleCache
class MyModelResource(ModelResource):
cache = SimpleCache(timeout=900)
class Meta:
queryset = MyModel.objects.all()
The problem: When I update the Resource by a PUT
request, the resource gets updated in DataBase, but doesn't get invalidated from cache, so I continue to get the old data for 15 minutes, which is inconvenient, I would like that when the resource get updated, it will be fetched from DB and cached again. Is there someone who faced the same issue ?
After a long search without finding any thing, I got an idea ! Override the PUT
method by just deleting the object from cache each time it gets updated, and this is the natural way that should happen from the beginning.
I found that Tastypie's SimpleCache is using Django's Core Cache (at least in this case; think settings), so here it is how I solved the problem:
from tastypie.resources import ModelResource
from my_app.models import MyModel
from tastypie.cache import SimpleCache
from django.core.cache import cache
class MyModelResource(ModelResource):
cache = SimpleCache(timeout=900)
class Meta:
queryset = MyModel.objects.all()
def put_detail(self, request, **kwargs):
# Build the key
key = "{0}:{1}:detail:pk={2}".format(kwargs['api_name'], kwargs['resource_name'], kwargs['pk'])
cache.delete(key)
return super(MyModelResource, self).put_detail(request, **kwargs)