我正在查看
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()
最佳答案 似乎Tastypie不会自动缓存列表,tastypie.resources在1027行附近:
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(列表视图)默认情况下.