如何在基于Django类的视图中使用@cache_page装饰器?

时间:2015-11-14 16:34:54

标签: python django

唯一可行的方法是在urls.py中添加装饰器,这很难看。

有没有办法在视图中应用这个装饰器?

class HomeView(View):
    @method_decorator(cache_page(60 * 60))
    def dispatch(self, *args, **kwargs):
        return super(HomeView, self).dispatch(*args, **kwargs)

我已尝试过上述内容,但似乎无法正常工作。

4 个答案:

答案 0 :(得分:3)

根据the docs,您可以使用// Create the service wrapper var conversation = watson.conversation ( { username: process.env.CONVERSATION_USERNAME || '<username>', password: process.env.CONVERSATION_PASSWORD || '<password>', version_date: '2016-07-11', version: 'v1' } ); // Endpoint to be called from the client side app.post ( '/api/message', function (req, res) { var payload = { workspace_id: workspace_id, context: {} }; if ( req.body ) { if ( req.body.input ) { payload.input = req.body.input; } if ( req.body.context ) { // The client must maintain context/state payload.context = req.body.context; } } // Send the input to the conversation service conversation.message ( payload, function (data) { return res.json ( data ); } ); 来装饰视图的method_decorator方法。最简洁的方式是这样的:

dispatch()

答案 1 :(得分:1)

method_decorator方法应该可以正常工作(我们在项目中使用它)。你确定这是问题吗?

这是我们正在使用的代码(名称已更改) - 看起来像你的

class MyClassView(CommonMixin, View):
    @method_decorator(cache_page(60*60, cache='cache1'))
    def get(self, request):
                .....

答案 2 :(得分:1)

我们要说我们要缓存 myView 视图的结果 -

from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def myView(request, year, month):
    text = "Displaying articles of : %s/%s"%(year, month)
    return HttpResponse(text)

和urls.py将是

urlpatterns = patterns('myapp.views',url(r'^articles/(?P<month>\d{2})/(?P<year>\d{4})/', 'myView', name = 'articles'),)

答案 3 :(得分:0)

在urls.py

中使用它
url(r'^home_url/?$', cache_page(60*60)(HomeView.as_view())),
相关问题