# 一:编写函数,(函数执行的时间用time.sleep(n)模拟) import time def index(): time.sleep(3) print('工具人')
# 二:编写装饰器,为函数加上统计时间的功能 import time def timeer(func): def upper(*args,**kwargs): start_time=time.time() func(*args,**kwargs) last_time=time.time() print('执行需要:',last_time - start_time) return upper @timeer def index(): time.sleep(3) print('工具人')
index()
# 三:编写装饰器,为函数加上认证的功能 def timeer(func): def upper(*args,**kwargs): name=input('请输入您的用户名').strip() psw=input('请输入您的密码').strip() if name =='zcy' and psw =='666': func(*args, **kwargs) else: print('账户密码输入错误') return upper @timeer def index(): time.sleep(3) print('工具人') index()
# 四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
# 注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
login_user=None def verify(func): def upper(*args,**kwargs): global login_user if not login_user: namer=input('请输入您的用户名:').strip() psd=input('请输入您的密码:').strip() with open('db',mode='r',encoding='utf-8') as f: for line in f: user_info = eval(line) if namer==user_info['name'] and psd==user_info['password']: print('认证成功') login_user =111 func(*args, **kwargs) else: print('认证失败') return upper() @verify def money(): print('钞能力') @verify def got(): print('提取')
# 五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录 login_user=None import time verify = {'login_time': 0,'out_time':5} def auth(func): def wrapper(*args,**kwargs): global login_user start_time = time.time() if login_user == None: print('请先登录。') name = input('请输入用户名:').strip() psd = input('请输入密码:').strip() with open(r'db.txt','r',encoding='utf-8') as f: for line in f: user_info = eval(line) if name == user_info['name'] and psd == user_info['password']: print('认证成功。') login_user = name func(*args, **kwargs)#如果登录时间超过5s下次执行指令需重新登录 verify['login_time'] = time.time() if verify['login_time'] - start_time > verify['out_time']: login_user = None else: print('认证失败。') else: func(*args,**kwargs) return wrapper @auth def money(): print('钞能力') @auth def got(): print('提取') money()