2012-04-18 92 views
3

我正在看tastypie caching docs並試圖建立自己的簡單緩存的事情,但緩存似乎並沒有被調用。當我訪問http://localhost:8000/api/poll/?format=json時,我得到了我的tastypie生成的json,但是我沒有從緩存類中得到輸出。爲什麼我的tastypie緩存沒有被調用?

from tastypie.resources import ModelResource 
from tastypie.cache import NoCache 
from .models import Poll 


class JSONCache(NoCache): 
    def _load(self): 
     print 'loading cache' 
     data_file = open(settings.TASTYPIE_JSON_CACHE, 'r') 
     return json.load(data_file) 

    def _save(self, data): 
     print 'saving to cache' 
     data_file = open(settings.TASTYPIE_JSON_CACHE, 'w') 
     return json.dump(data, data_file) 

    def get(self, key): 
     print 'jsoncache.get' 
     data = self._load() 
     return data.get(key, None) 

    def set(self, key, value, timeout=60): 
     print 'jsoncache.set' 
     data = self._load() 
     data[key] = value 
     self._save(data) 


class PollResource(ModelResource): 
    class Meta: 
     queryset = Poll.objects.all() 
     resource_name = 'poll' 
     cache = JSONCache() 

回答

7

似乎Tastypie確實圍繞線1027不會自動緩存列表,tastypie.resources

def get_list(self, request, **kwargs): 

    # ... 

    # TODO: Uncached for now. Invalidation that works for everyone may be 
    #  impossible. 
    objects = self.obj_get_list(
     request=request, **self.remove_api_resource_names(kwargs)) 

    # ... 

,而與細節(左右線1050):

def get_detail(self, request, **kwargs): 

    # ... 

    try: 
     obj = self.cached_obj_get(
      request=request, **self.remove_api_resource_names(kwargs)) 

    # ... 

...注意在前面的片段obj_get_list被調用而不是cached_obj_get_list。也許重寫get_list和使用cached_obj_get_list將允許您在這裏使用緩存?

現在,您可能會從您的班級輸出http://localhost:8000/api/poll/<pk>/?format=json(詳細視圖),但默認情況下不會顯示http://localhost:8000/api/poll/?format=json(列表視圖)。

+0

我正在使用tastypie.in該案件不起作用 – RahulG 2015-05-20 11:30:49

相關問題