<> demand ? Multiple decorators act on a function , For example, there are two decorators @login, @allow, I want to judge whether the user logs in first , Then judge whether the user has permission
<> An example explanation python Execution sequence of decorator ( Copy from others ), There's a problem here, so write it down
def decorator_a(func): print('Get in decorator_a') def
inner_a(*args,**kwargs): print('Get in inner_a') res = func(*args,**kwargs)
return res return inner_a def decorator_b(func): print('Get in decorator_b')
def inner_b(*args,**kwargs): print('Get in inner_b') res = func(*args,**kwargs)
return res return inner_b @decorator_b @decorator_a def f(x): print('Get in f')
return x * 2
result
Get in decorator_a
Get in decorator_b
<>
seem , The decorator has started executing in reverse order when the function is defined . If it is used here decorator_b(decorator_a(f)), The result is the same . But there's a problem , If I create a new decorator with parameters C
def decorator_c(nums): print("Get in decorator_c") def wrapper(func):
print("Get in wrapper_c") def inner_c(*args, **kwargs): print('Get in inner_c')
res = func(*args, **kwargs)+nums return res return inner_c return wrapper
@decorator_c(10) @decorator_b @decorator_a def f(x): print('Get in f') return x
* 2
<> At this time, the implementation result is
Get in decorator_c
Get in decorator_a
Get in decorator_b
Get in wrapper_c
<> This is the order of execution when defined , The most important thing is the order of execution , implement f(1).
Get in inner_c
Get in inner_b
Get in inner_a
Get in f
Obviously , After a series of decorator definitions , Now the function can be expressed like this :inner_c(… return inner_b(… return
inner_a(…return f(1)))), stay inner_c Returned in func yes inner_b,inner_b What is returned is inner_a,
inner_a return f,inner_c —>inner_b —>inner_a , Sequential execution ,inner_c The decoration part of the code is executed first .
So if you need to implement , Log in first, then judge the authority , should
@login
@allow
def get_user_department():
pass
Technology