我想了解發布在this blog post上的mixins的代碼。爲什麼我需要用@method_decorator裝飾login_required裝飾器
這些混入從混入內django.contrib.auth.decorators
致電login_required
裝飾,但他們這樣做由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)