为什么我需要使用@method_decorator来装饰login_required装饰器

har*_*jay 10 django decorator login-required django-class-based-views

我想了解这篇博客文章中发布的mixins的代码.

这些mixin login_required从mixins中调用装饰器django.contrib.auth.decorators,但是它们是由method_decoratorfrom来装饰的django.utils.decorators.在下面的示例代码中,我不明白为什么我需要装饰login_required装饰器.

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
class LoginRequiredMixin(object):
    """
    View mixin which verifies that the user has authenticated.

    NOTE:
        This should be the left-most mixin of a view.
    """
    # Why do I need to decorate login_required here
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(LoginRequiredMixin, self).dispatch(*args, **kwargs) 
Run Code Online (Sandbox Code Playgroud)

method_decorator装饰说它是用来"功能装饰转换为一个方法装饰"但在测试代码,我可以用我的装饰,即使没有method_decorator.

我的装饰师

def run_eight_times(myfunc):
    def inner_func(*args, **kwargs):
        for i in range(8):
            myfunc(*args, **kwargs)
    return inner_func 
Run Code Online (Sandbox Code Playgroud)

调用上面装饰器的我的类直接生成相同的结果,就像我调用装饰的装饰器一样 method_decorator

from django.utils.decorators import method_decorator
class Myclass(object):

    def __init__(self,name,favorite_dish):
        self.name = name
        self.favorite_dish = favorite_dish

    # This next line is not required
    #@method_decorator(run_eight_times)
    @run_eight_times
    def undecorated_function(self):
        print "%s likes spam in his favorite dish %s" % (self.name,self.favorite_dish) 
Run Code Online (Sandbox Code Playgroud)

Mik*_*gel 16

Django的method_decorator设置为将self参数正确传递给修饰函数.这并不在你上面写的测试案例出现的原因run_eight_times装饰是,inner_funcrun_eight_times盲目中MYFUNC通过传递所有参数*args**kwargs.一般情况下,情况并非如此.

要通过示例查看此内容,请尝试以下操作:

from django.utils.decorators import method_decorator

def run_eight_times(myfunc):
    def inner_func(what_he_likes, **kwargs):
        # override...
        what_he_likes = 'pizza'
        for i in range(8):
            myfunc(what_he_likes, **kwargs)
    return inner_func

class MyClass(object):

    def __init__(self, name, favorite_dish):
        self.name = name
        self.favorite_dish = favorite_dish

    # This next line required!
    @method_decorator(run_eight_times)
    #@run_eight_times
    def undecorated_function(self, what_he_likes):
        print "%s likes %s in his favorite dish %s" % (
            self.name, what_he_likes, self.favorite_dish
        )

def main():
    inst = MyClass('bob', 'burrito')
    inst.undecorated_function('hammy spam')

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

具体来说,Django的视图装饰器将返回一个带签名的函数(request, *args, **kwargs).对于基于类的视图,这应该是(self, request, *args, **kwargs).这就是method_decorator做 - 将第一个签名转换为第二个签名.