Django - 基于非class的视图授权
Django - Non-class-based views authorization
我遵循本教程http://www.effectivedjango.com/tutorial/authzn.html。我们在那里创建 class,我们应该使用基于 class 的视图对其进行扩展。那么如果我有方法定义的视图呢?我该怎么办?
def some_private_view(request):
...
class LoggedInMixin(object):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoggedInMixin, self).dispatch(*args, **kwargs)
您使用 login_required
装饰器 https://docs.djangoproject.com/en/1.8/topics/auth/default/#the-login-required-decorator。
你不能装饰一个class,因为装饰器是一个以函数x
为参数的函数,用这个函数x
和[=34做一些事情=] 之后。这就是为什么你在这里需要 "useless" dispatch
方法,它只是调用它的父级而不做任何事情,因为 class 不是函数。
编辑:稍后注意 - 如果您想跳过 "useless" dispatch
方法,您可以编写一个 Mixin(一个小的 class,它只是覆盖一个特定的函数),它只是添加 @method_decorator(login_required)to
dispatchand use it with all
View`s.
您实际上不需要这样做。 django braces 可以为您完成这项工作。那么你可以这样做:
class AdminView(braces.views.LoginRequiredMixin, View):
def get(request, *args, **kwargs):
pass # Do some logged-in user stuff here
我遵循本教程http://www.effectivedjango.com/tutorial/authzn.html。我们在那里创建 class,我们应该使用基于 class 的视图对其进行扩展。那么如果我有方法定义的视图呢?我该怎么办?
def some_private_view(request):
...
class LoggedInMixin(object):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoggedInMixin, self).dispatch(*args, **kwargs)
您使用 login_required
装饰器 https://docs.djangoproject.com/en/1.8/topics/auth/default/#the-login-required-decorator。
你不能装饰一个class,因为装饰器是一个以函数x
为参数的函数,用这个函数x
和[=34做一些事情=] 之后。这就是为什么你在这里需要 "useless" dispatch
方法,它只是调用它的父级而不做任何事情,因为 class 不是函数。
编辑:稍后注意 - 如果您想跳过 "useless" dispatch
方法,您可以编写一个 Mixin(一个小的 class,它只是覆盖一个特定的函数),它只是添加 @method_decorator(login_required)to
dispatchand use it with all
View`s.
您实际上不需要这样做。 django braces 可以为您完成这项工作。那么你可以这样做:
class AdminView(braces.views.LoginRequiredMixin, View):
def get(request, *args, **kwargs):
pass # Do some logged-in user stuff here