簡體   English   中英

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的Core Cache(至少在這種情況下;請考慮設置),因此這就是我解決問題的方法:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM