问题描述
阅读ProDjango这本书,我发现有兴趣在基于类视图的方法中应用自定义装饰器。
Reading a 'ProDjango' book, I've found interesting moment about applying custom decorator to methods in class-based views.
作者说我们可以手动将装饰器分配给每个类的方法,即 get
, post
等等,或者我们可以将我们的装饰器添加到 dispatch()
方法,如果我们这样做,那么装饰器将被应用于每个类的方法( get
, post
等)
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
如下所示:。
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开始,您现在可以在类级别使用方法装饰器。您将需要传递要装饰的方法的名称。所以没有必要重新调度,只是为了应用装饰器。
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中应用装饰器做调度方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!