Python基础-----带参数验证功能的装饰器

#带参数,可以根据不同的认证类型进行认证

user_list = [
{'name':'a','password':'123'},
{'name':'b','password':'123'},
{'name':'c','password':'123'},
{'name':'d','password':'123'}
] #所有用户信息列表(值为字符串类型)

current_user = {'username':None,'login':False} #记录用户当前登录状态

def auth(auth_type = 'filedb'): #最外层闭包函数传入验证类型auth_type
def auth_func(func):
def wrapper(*args,**kwargs):
print('认证类型是:',auth_type)
if auth_type == 'filedb': #用阿里判断是何种认证类型
if current_user['username'] and current_user['login']: #如果已经登录,则无需登陆
res = func(*args,**kwargs)
return res
username = input('用户名:').strip() #上面if不成立,则登录
password = input('密码:').strip()
for user_dic in user_list: #for遍历的是用户列表的中用户信息字典
if username == user_dic['name'] and password == user_dic['password']: #登录验证
current_user['username'] = username #登录成功,更改用户状态
current_user['login'] = True
res = func(*args,**kwargs)
return res
else: #该处else没放在if下是因为,要遍历所有的用户列表才能判断是否真的有错
print('用户名或密码错误,请重新登录!')
elif auth_type == 'ladb':
print('认证类型是:',auth_type)
res = func(*args,**kwargs)
return res
return wrapper
return auth_func

@auth(auth_type = 'filedb') #auth_func = auth(auth_type = 'filedb') --> @auth_func,给他附加了参数
def home(name):
print('欢迎 %s 来到主页'%name)

@auth(auth_type = 'ladb')
def shopping_car(name):
print('%s 的购物车里有:学习用品,生活用品!'%name)

home('Jerry')
print(current_user)
shopping_car('Jerry')
原文地址:https://www.cnblogs.com/Meanwey/p/9741287.html