使用基于类的视图缓存页面

2024-04-29 00:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用基于类的视图(TemplateView)来缓存页面,但我不能。我遵循了这里的说明:

Django--URL Caching Failing for Class Based Views

以及这里:

https://github.com/msgre/hazard/blob/master/hazard/urls.py

但我有个错误:

cache_page has a single mandatory positional argument: timeout

我读了缓存页的代码,它有以下内容:

if len(args) != 1 or callable(args[0]):
    raise TypeError("cache_page has a single mandatory positional argument: timeout")
cache_timeout = args[0]

这意味着它不允许超过一个参数。有没有其他方法让缓存页工作??我已经研究这个有一段时间了。。。

看来以前的解决方案已经行不通了


Tags: django视图urlcachepagetimeoutargs页面
3条回答

根据caching docs,在url中缓存CBV的正确方法是:

from django.views.decorators.cache import cache_page

url(r'^my_url/?$', cache_page(60*60)(MyView.as_view())),

请注意,您链接到的答案已过期。使用decorator的旧方法已被删除(changeset)。

又一个很好的例子CacheMixin from cyberdelia github

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)

用例:

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"

您可以简单地修饰类本身,而不是重写分派方法或使用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):
...

关于decorating a method within a class based view.的Django文档

相关问题 更多 >