如何在基于类的视图 Django 中应用装饰器执行调度方法 [英] How to apply decorator do dispatch method in class-based views Django

查看:22
本文介绍了如何在基于类的视图 Django 中应用装饰器执行调度方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读ProDjango"一书,我发现将自定义装饰器应用于基于类的视图中的方法的有趣时刻.

Reading a 'ProDjango' book, I've found interesting moment about applying custom decorator to methods in class-based views.

作者说我们可以手动为类的每个方法分配装饰器,即getpost等,或者我们可以将我们的装饰器添加到dispatch() 方法,如果我们这样做,那么装饰器将应用于类的每个方法(getpost 等)

Author says that we can either manually assign decorator to each method of class, i.e., get, post and so on, or we can add our decorator to dispatch() method and if we do so then decorator will be applied to each method of class(get, post etc)

问题是:

我实际上如何将装饰器应用于基于类的视图的 dispatch() 方法?

How actually I can apply decorator to dispatch() method of Class-based view?

推荐答案

您可以使用 method_decorator 装饰器,如 docs.

You can use the decorator method_decorator as shown here in the docs.

来自文档:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

class ProtectedView(TemplateView):
    template_name = 'secret.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ProtectedView, self).dispatch(*args, **kwargs)

或者你可以在你的 urls.py:

Or you can do it in your urls.py:

from django.conf.urls import patterns
from django.contrib.auth.decorators import login_required
from myapp.views import MyView

urlpatterns = patterns('',
    (r'^about/', login_required(MyView.as_view())),
)

更新:

从 Django 1.9 开始,您现在可以在类级别使用方法装饰器.您需要传递要装饰的方法的名称.所以没有必要为了应用装饰器而覆盖 dispatch.

Update:

As of Django 1.9, you can now use the method decorator at the class level. You will need to pass the name of the method to be decorated. So there's no need to override dispatch just to apply the decorator.

示例:

@method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
    template_name = 'secret.html'

此外,您可以定义一个装饰器列表或元组并使用它来代替多次调用 method_decorator().

Moreover, you can define a list or tuple of decorators and use this instead of invoking method_decorator() multiple times.

示例(以下两个类相同):

Example(the two classes below are the same):

decorators = [never_cache, login_required]

@method_decorator(decorators, name='dispatch')
class ProtectedView(TemplateView):
    template_name = 'secret.html'

@method_decorator(never_cache, name='dispatch')
@method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
    template_name = 'secret.html'

这篇关于如何在基于类的视图 Django 中应用装饰器执行调度方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆