为什么我的tastypie缓存没有被调用?

时间:2012-04-18 23:47:55

标签: python django tastypie

我正在查看tastypie caching docs并尝试设置我自己的简单缓存,但缓存似乎没有被调用。当我访问http://localhost:8000/api/poll/?format=json时,我得到了我的tastypie生成的json,但是我没有得到缓存类的输出。

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

1 个答案:

答案 0 :(得分:7)

似乎Tastypie不会自动缓存tastypie.resources1027周围的列表:

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(列表视图)。