2019年3月10日 装饰器进阶-模拟session

ser_dic={'username':None,'login':False}#用户字典,反应登入状态,用字典做全局变量

def idf(func):#验证登入信息是否正确
def wrapper(*args,**kwargs):
if user_dic['username'] and user_dic['login']:#验证登入状态,如果正确登入,则直接执行
print("验证通过")
res = func(*args, **kwargs)
return res
else:
username=input('please input username: '.strip())#.strip指的是移除前后空格或者制表符
password=input('pleasr input password: ')
if username=='sxj' and password=='abc':
user_dic['username']=username#更新用户字典的登入状态
user_dic['login']=True#更新用户字典的登入状态
print("验证通过")
res = func(*args, **kwargs)
return res
else:
print('I am sorry')
return wrapper @idf
def index():
print('welcome to index') @idf
def home(name):
print('%s,welcome to home'%name) @idf
def shopping_car():
print('this is shopping car,you have %s,%s,%s'%('奶茶','妹妹','sxj')) home('sxj')
shopping_car()

>>>>

please input username:sxj
pleasr input password: abc
验证通过
sxj,welcome to home
验证通过
this is shopping car,you have 奶茶,妹妹,sxj

难度增加:

user_list=[#定义密码库
{'name':'sxj','password':''},
{'name':'abc','password':''},
{'name':'def','password':''},#注意这里的222是字符串类型
{'name':'ghw','password':333}#注意这里的333是int 类型
]
current_dic={'username':None,'login':False}#用户字典,反应登入状态,用字典做全局变量 def idf(func):#验证登入信息是否正确
def wrapper(*args,**kwargs):
if current_dic['username'] and current_dic['login']:#验证登入状态,如果正确登入,则直接执行
print("验证通过")
res = func(*args, **kwargs)
return res
else:
user_name=input('please input username: '.strip())#.strip指的是移除前后空格或者制表符
pass_word=input('please input password: '.strip())#注意这里输入的是字符串 与上面的333会因为类型不同导致密码错误
for u_dic in user_list:
if u_dic['name'] == user_name and str(u_dic['password'])== pass_word: #为了防止发生类型不同,所以用str强制转化为字符串类型
current_dic['username']=user_name#更新用户字典的登入状态
current_dic['login']=True#更新用户字典的登入状态
print("验证通过")
res = func(*args, **kwargs)
return res
else:
print('I am sorry')
return wrapper @idf
def index():
print('welcome to index') @idf
def home(name2):
print('%s,welcome to home'%name2) @idf
def shopping_car():
print('this is shopping car,you have %s,%s,%s'%('奶茶','妹妹','sxj')) print('First>',current_dic)
home('sxj')
print('Last>',current_dic)
shopping_car()

》》》》

First> {'username': None, 'login': False}
please input username:ghw
please input password:333
验证通过
sxj,welcome to home
Last> {'username': 'ghw', 'login': True}
验证通过
this is shopping car,you have 奶茶,妹妹,sxj

上一篇:MySQL日志管理、备份与恢复


下一篇:mysql 备份