【问题标题】:Why doesn't my tastypie cache get called?为什么我的 sweetpie 缓存没有被调用?
【发布时间】:2012-04-18 23:47:55
【问题描述】:

我正在查看tastypie caching docs 并尝试设置我自己的简单缓存,但似乎没有调用缓存。当我访问http://localhost:8000/api/poll/?format=json 时,我得到了我的tastepie 生成的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()

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

    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))
    
       # ...
    

    ...请注意,在以前的 sn-p 中,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(列表视图)的默认输出。

    【讨论】:

      猜你喜欢
      • 2011-05-17
      • 1970-01-01
      • 2016-09-28
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多