Django内置method_decorator
method_decorator属于django.utils.decorators,用于将函数装饰器转为类方法装饰器,直白的说,就是被method_decorator包裹的装饰器可用于装饰类或类方法。
用法
1.装饰类方法
将需要的装饰器包裹在method_decorator中装饰在目标类方法上。
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().dispatch(*args, **kwargs)
2.装饰类
method_decorator可以直接装饰一个类,但这样做需要给定’name’参数,即指明装饰类中的哪些方法。对于类试图而言,这些方法主要包括dispatch(), get(), post(), delete()等。
@method_decorator(login_required<