# 装饰器相关 def auth(func): def inner(*args,**kwargs): return func(*args,**kwargs) return inner @auth def login(): pass print(login.__name__) # inner
# 使用functools,虽然执行的还是inner函数,但名字不叫inner import functools def auth(func): @functools.wraps(func) def inner(*args,**kwargs): return func(*args,**kwargs) return inner @auth def login(): pass @auth def index(): pass print(login.__name__) # login print(index.__name__) # index
1 # 一个函数可以被多个装饰器装饰 2 # 先执行离他最近的装饰器, 3 4 import functools 5 6 def auth0(func): 7 print("00000000000") 8 @functools.wraps(func) 9 def inner(*args,**kwargs): 10 return func(*args,**kwargs) 11 return inner 12 13 def auth1(func): 14 print("1111111111111111111") 15 @functools.wraps(func) 16 def inner(*args,**kwargs): 17 return func(*args,**kwargs) 18 return inner 19 20 @auth0 21 @auth1 22 def index(): 23 pass
from flask import Flask import functools app=Flask(__name__) def auth(func): @functools.wraps(func) def inner(*args,**kwargs): return func(*args,**kwargs) return inner @app.route('/index') @auth def index(): return 'hello world' @app.route('/login') @auth def login(): return 'hello world' if __name__ == '__main__': app.run() # flask 加装饰器 # 1、必须引用functools # 2、装饰器必须放在@app.route('/login')的下面,因为url必须和@auth # def index(): # return 'hello world'创建关系