【问题标题】:Tastypie: Is there a way to invalidate Cache after resource Update?Tastypie:有没有办法在资源更新后使缓存失效?
【发布时间】:2017-10-30 18:48:16
【问题描述】:

我有一个 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请求更新资源时,资源在DataBase中得到更新,但没有从缓存中失效,所以我继续获取15分钟的旧数据,这很不方便,我希望当资源更新时,它将从数据库中获取并再次缓存。有没有遇到同样问题的人?

【问题讨论】:

  • @e4c5 不,不是。
  • 是包不同,但核心问题和解决方法是一样的
  • @e4c5 没有核心问题不一样,解决方法也不是很实用。我深入研究了 Tastypie 和 Django Caching 并找到了一个高效且直接的解决方案!
  • 然后发布或删除问题

标签: django rest caching tastypie


【解决方案1】:

经过长时间的搜索但没有找到任何东西,我有了一个想法!覆盖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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2020-10-23
    • 2012-08-17
    • 2023-01-20
    • 2016-04-19
    • 1970-01-01
    相关资源
    最近更新 更多