# 无参装饰器的模板 # def outter(func): # def wrapper(*args,**kwargs): # res=func(*args,**kwargs) # return res # return wrapper import time user_info={'current_user':None} def auth(func): def wrapper(*args,**kwargs): if user_info['current_user'] is not None: res=func(*args,**kwargs) return res inp_user=input('username>>>: ').strip() inp_pwd=input('password>>>: ').strip() if inp_user == 'egon' and inp_pwd == '123': # 记录登录状态 user_info['current_user']=inp_user print('login successful') res=func(*args,**kwargs) return res else: print('user or password error') return wrapper @auth def index(): """这是index功能""" print('welcome to index page') time.sleep(2) return 123 @auth def home(name): """这是home功能""" print('welcome %s to home page' %name) time.sleep(1) # index() # home('egon') # 有参装饰器 def outter2(xxx,yyy): def outter(func): def wrapper(*args,**kwargs): res=func(*args,**kwargs) print(xxx) print(yyy) return res return wrapper return outter import time user_info={'current_user':None} def auth2(engine='file'): def auth(func): def wrapper(*args,**kwargs): if user_info['current_user'] is not None: res=func(*args,**kwargs) return res inp_user=input('username>>>: ').strip() inp_pwd=input('password>>>: ').strip() if engine == 'file': print('基于文件的认证') if inp_user == 'egon' and inp_pwd == '123': # 记录登录状态 user_info['current_user']=inp_user print('login successful') res=func(*args,**kwargs) return res else: print('user or password error') elif engine == 'mysql': print('基于mysql数据的认证') elif engine == 'ldap': print('基于ldap的认证') else: print('无法识别认证源') return wrapper return auth @auth2(engine='mysql') # @auth ===> index=auth(最原始那个index的内存地址)===》index=wrapper def index(): """这是index功能""" print('welcome to index page') time.sleep(2) return 123 @auth2(engine='file') def home(name): """这是home功能""" print('welcome %s to home page' %name) time.sleep(1) index() #wrapper() home('egon')