登陆验证代码.
- # 用户验证功能, 不修改源代码, 使用装饰器.
- user_dic={'username':None,'login':False} #定义全局变量
- def auth_func(func):
- def wrapper(*args,**kwargs):
- if user_dic['username'] and user_dic['login']:
- res = func(*args, **kwargs)
- return res
- user_name = input('用户名:').strip() #删除首尾空格
- pass_wd = input('用户密码:').strip()
- if user_name == 'w' and pass_wd == '123':
- user_dic['username'] = user_name
- user_dic['login'] = True
- res = func(*args, **kwargs)
- return res
- else:
- print('用户名或密码输入错误')
- return wrapper
- @auth_func
- def index():
- print('1234564897')
- return 5
- @auth_func
- def home(name):
- print('%s 欢迎回家'%name)
- @auth_func
- def shopping_car(name):
- print('%s 购物车里面有 [%s,%s,%s]'%(name,'手机','笔记本','数码相机'))
- index()
- home('123')
- shopping_car('产品经理')
- user_list=[
- {'name':'alex','passwd':'123'},
- {'name':'linhaifeng','passwd':'456'},
- {'name':'wupeiqi','passwd':'789'},
- {'name':'yuanhao','passwd':'123'},
- ]
- # for user_dic in user_list: #遍历列表字典
- # # print(user_dic.keys(),user_dic.values())
- # a = user_dic['name']
- # b = user_dic['passwd']
- # print(a)
- # print(b)
- #用户验证功能, 不修改源代码, 使用装饰器.
- current_dic={'username':None,'login':False} #定义全局变量
- def auth_func(func):
- def wrapper(*args,**kwargs):
- if current_dic['username'] and current_dic['login']:
- res = func(*args, **kwargs)
- return res
- user_name = input('用户名:').strip() #删除首尾空格
- pass_wd = input('用户密码:').strip()
- for user_dic in user_list: #遍历列表字典 (字典包含账号, 密码)
- if user_name == user_dic['name'] and pass_wd == user_dic['passwd']:
- current_dic['username'] = user_name #保存全局变量
- current_dic['login'] = True #保存全局变量
- res = func(*args, **kwargs)
- return res
- else:
- print('用户名或者密码错误')
- return wrapper
- @auth_func
- def index():
- print('1234564897')
- return 5
- @auth_func
- def home(name):
- print('%s 欢迎回家'%name)
- @auth_func
- def shopping_car(name):
- print('%s 购物车里面有 [%s,%s,%s]'%(name,'手机','笔记本','数码相机'))
- index()
- print('用户 ---',current_dic)
- home('123')
- print('用户 ---',current_dic)
- shopping_car('产品经理')
来源: http://www.bubuko.com/infodetail-2775230.html