python多个装饰器

'''
在装饰器中加上参数:
1.实现在源代码中加上时间统计:函数timmer
2.实现用户名认证功能:函数auth2
3.实现一次认证,刷新后自动登录功能,index函数已经认证并登录,
在执行home函数时不需要登录直接进入
'''

import time
current_login={'name':None,'login':False}

def timmer(func):#func为home的内存对象,func=home
def wrapper(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs)#home(name) 调最原始的home
stop_time=time.time()
print('run time is %s' %(stop_time-start_time))
return res
return wrapper

def auth2(auth_type='file'):
def auth(func):
# print(auth_type)
def wrapper(*args,**kwargs):
if current_login['name'] and current_login['login']:
res=func(*args,**kwargs)
return res
if auth_type == 'file':
name=input('username: ')
password=input('password: ')
if name == 'wang' and password == '123':
print('auth successfull')
res=func(*args,**kwargs)
current_login['name']=name
current_login['login']=True
return res
else:
print('auth error')
elif auth_type == 'sql':
print('sql还没有学。。。')
return wrapper
return auth

@timmer #添加多个装饰器
@auth2(auth_type='file') #@auth #index=auth(index)
def index():
print('welcome to inex page')

@auth2()
def home():#home=auth(home)
print('welcome to home page')

#调用阶段
index()
home()
原文地址:https://www.cnblogs.com/hanhan914-wang/p/7495828.html