KVI*_*ISH 27 django django-class-based-views
我正在尝试使用基于类的视图(TemplateView)执行cache_page,但我无法做到.我按照这里的说明:
以及这里:
https://github.com/msgre/hazard/blob/master/hazard/urls.py
但我得到这个错误:
cache_page has a single mandatory positional argument: timeout
Run Code Online (Sandbox Code Playgroud)
我读了cache_page的代码,它有以下内容:
if len(args) != 1 or callable(args[0]):
raise TypeError("cache_page has a single mandatory positional argument: timeout")
cache_timeout = args[0]
Run Code Online (Sandbox Code Playgroud)
这意味着它不会允许超过1个参数.有没有其他方法让cache_page工作?我一直在挖这个...
似乎以前的解决方案不再适用
Ala*_*air 50
根据缓存文档 docs,缓存CBV的正确方法是
from django.views.decorators.cache import cache_page
url(r'^my_url/?$', cache_page(60*60)(MyView.as_view())),
Run Code Online (Sandbox Code Playgroud)
请注意,您链接的答案已过期.旧的使用装饰器的方法已被删除(变更集).
mad*_*rdi 19
另一个来自cyberdelia github的好例子CacheMixin
class CacheMixin(object):
cache_timeout = 60
def get_cache_timeout(self):
return self.cache_timeout
def dispatch(self, *args, **kwargs):
return cache_page(self.get_cache_timeout())(super(CacheMixin, self).dispatch)(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
用例:
from django.views.generic.detail import DetailView
class ArticleView(CacheMixin, DetailView):
cache_timeout = 90
template_name = "article_detail.html"
queryset = Article.objects.articles()
context_object_name = "article"
Run Code Online (Sandbox Code Playgroud)
您可以简单地装饰类本身,而不是覆盖调度方法或使用mixin.
例如
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator
@method_decorator(cache_page(60 * 5), name='dispatch')
class ListView(ListView):
...
Run Code Online (Sandbox Code Playgroud)
Django 在基于类的视图中装饰方法.
您可以将其添加为类装饰器,甚至可以使用列表添加多个:
@method_decorator([vary_on_cookie, cache_page(900)], name='dispatch')
class SomeClass(View):
...
Run Code Online (Sandbox Code Playgroud)