python装饰器执行顺序,Django中一个视图的多个装饰器:执行顺序

I am trying to decorate a Django view by two decorators, one for checking login, and one for checking is_active.

The first one is the built-in @login_required, and the second one is the following:

def active_required(function):

dec = user_passes_test(lambda u: u.is_active, '/notallowed', '')

return dec(function)

Now, the decorators in Python work inside out, however the following does not work:

@active_required

@login_required

def foo(request):

...

I want to first check if the user is logged in, and redirect to login page if not, and if he or she is logged in, I want to check whether he or she is active, and if not, perform redirect to '/notallowed'.

What happens is that if the login_required fails, the user is not redirected to the login page, but @active_required is executed, and since the user is null in that case, @active_required decorator fails and the user is redirected to /notallowed.

Changing the order seems to work,

@login_required

@active_required

def foo(request):

...

but I suspect there is something wrong with this approach too.

What is the proper way to combine two decorators, and why does the execution order differ from simple Python decorators?

解决方案Now, the decorators in Python work inside out

Well i guess that depends on your definition of inside out. in your case you want login_required to execute first, and so it should be the "outermost" (top) decorator

as you noted, your last example works, and is indeed the correct way to do this

edit

maybe the confusion is with how (these particular) decorators work

login_required(original_view) returns a new view, which first checks if you are logged in, and then calls original_view

so

login_required(

active_required(

my_view

)

)

first checks if you are logged in, then

first(second) checks if you are active, then

runs my_vew

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值