10.带参数验证功能装饰器
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 user_list=[ 4 {'name':'alex','passwd':'123'}, 5 {'name':'linhaifeng','passwd':'123'}, 6 {'name':'wupeiqi','passwd':'123'}, 7 {'name':'yuanhao','passwd':'123'}, 8 ] 9 current_dic={'username':None,'login':False} 10 11 def auth(auth_type='filedb'): 12 def auth_func(func): 13 def wrapper(*args,**kwargs): 14 print('认证类型是',auth_type) 15 if auth_type == 'filedb': 16 if current_dic['username'] and current_dic['login']: 17 res = func(*args, **kwargs) 18 return res 19 username=input('用户名:').strip() 20 passwd=input('密码:').strip() 21 for user_dic in user_list: 22 if username == user_dic['name'] and passwd == user_dic['passwd']: 23 current_dic['username']=username 24 current_dic['login']=True 25 res = func(*args, **kwargs) 26 return res 27 else: 28 print('用户名或者密码错误') 29 elif auth_type == 'ldap': 30 print('鬼才特么会玩') 31 res = func(*args, **kwargs) 32 return res 33 else: 34 print('鬼才知道你用的什么认证方式') 35 res = func(*args, **kwargs) 36 return res 37 38 return wrapper 39 return auth_func 40 41 @auth(auth_type='filedb') #auth_func=auth(auth_type='filedb')-->@auth_func 附加了一个auth_type --->index=auth_func(index) 42 def index(): 43 print('欢迎来到京东主页') 44 45 @auth(auth_type='ldap') 46 def home(name): 47 print('欢迎回家%s' %name) 48 # 49 @auth(auth_type='sssssss') 50 def shopping_car(name): 51 print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃')) 52 53 # print('before-->',current_dic) 54 # index() 55 print('after--->',current_dic) 56 home('产品经理') 57 # shopping_car('产品经理')