Tastypie:有没有办法在资源更新后使缓存失效?

Tastypie: Is there a way to invalidate Cache after resource Update?

我有一个 Django (1.8.17) 应用程序,我正在使用 Tastypie (0.13.3) 作为 REST API 框架。 我有一些非常简单的资源,我使用 SimpleCache 缓存它们 15 分钟。

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

问题:当我通过 PUT 请求更新资源时,资源在数据库中得到更新,但不会从缓存中失效,所以我继续获取旧数据 15 分钟,这很不方便,我希望当资源更新时,它将从数据库中获取并再次缓存。有人遇到同样的问题吗?

找了半天没有找到任何东西,我有了一个主意!通过在每次对象更新时从缓存中删除对象来覆盖 PUT 方法,这是从一开始就应该发生的自然方式。 我发现 Tastypie 的 SimpleCache 正在使用 Django 的核心缓存(至少在这种情况下;想想设置),所以这就是我解决问题的方法:

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)