gpt4 book ai didi

django - 为什么需要用@method_decorator装饰login_required装饰器

转载 作者:行者123 更新时间:2023-12-04 03:16:34 26 4
gpt4 key购买 nike

我正在尝试了解this blog post上发布的mixins的代码。

这些mixins从mixins中的login_required调用django.contrib.auth.decorators装饰器,但它们通过method_decorator中的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)
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

我的调用上述装饰器的类直接产生与调用 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)

最佳答案

Django的method_decorator设置为将self参数正确传递给装饰函数。在您上面用run_eight_times装饰器编写的测试用例中未显示出来的原因是,inner_func中的run_eight_times盲目地通过*args**kwargs将所有参数传递给myfunc。通常,情况并非如此。

要在您的示例中看到它,请尝试以下操作:

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()

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

关于django - 为什么需要用@method_decorator装饰login_required装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9560840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com