1 # 一:编写函数,(函数执行的时间用time.sleep(n)模拟) 2 import time 3 def foo(x,y): 4 time.sleep(2) 5 print(x,y) 6 # 二:编写装饰器,为函数加上统计时间的功能 7 import time 8 def timmer(func): 9 def wrapper(*args,**kwargs): 10 start = time.time() 11 res = func(*args,**kwargs) 12 stop = time.time() 13 print(stop - start) 14 return res 15 return wrapper 16 @timmer 17 def foo(x,y): 18 time.sleep(2) 19 print(x,y) 20 21 foo(1,2) 22 # 三:编写装饰器,为函数加上认证的功能 23 def login(func): 24 def wrapper(*args,**kwargs): 25 while True: 26 username = input('请输入账号:').strip() 27 userpwd = input('请输入密码:').strip() 28 if username == 'yu' and userpwd != '123': 29 print('登陆成功') 30 res = func(*args,**kwargs) 31 return res 32 else: 33 print('账号错误请重新输入') 34 continue 35 return wrapper 36 @login 37 def foo(x,y): 38 time.sleep(2) 39 print(x,y) 40 foo(1,2) 41 # 四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码 42 # 注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式 43 flag = False 44 def login(func): 45 def wrapper(*args,**kwargs): 46 global flag 47 if not flag: 48 with open('account', mode='r',encoding='utf-8') as f: 49 data = f.readline() 50 dic = eval(data) 51 while True: 52 username = input("username>>>: ").strip() 53 password = input("password>>>: ").strip() 54 if username == dic['name'] and dic['password'] == password: 55 flag = True # 修改用户登录状态 56 print("登陆成功") 57 res = func(*args,**kwargs) # 执行传入的函数 58 return res 59 else: 60 print('账号密码不匹配') 61 continue 62 else: 63 print('已通过验证') 64 func(*args,**kwargs) 65 return wrapper 66 @login 67 def foo(): 68 print('hallo world') 69 @login 70 def fun(x,y,z): 71 print(x+y+z) 72 foo() 73 fun(1,2,3) 74 # 五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录 75 import time,datetime 76 user = {'user':None,'start_time':None,'login_time':1} 77 def login(func): 78 def wrapper(*args,**kwargs): 79 if user['user']: 80 time1 = (datetime.datetime.fromtimestamp(time.time()) - user['start_time']).seconds 81 if time1 < int(user['login_time']): 82 return func(*args, **kwargs) 83 else: 84 print("登录时间过长,请重新登录!") 85 with open('account', mode='r',encoding='utf-8') as f: 86 data = f.readline() 87 dic = eval(data) 88 while True: 89 username = input("username>>>: ").strip() 90 password = input("password>>>: ").strip() 91 92 if username == dic['name'] and dic['password'] == password: 93 print("登陆成功") 94 user['user'] = username 95 user['start_time'] = datetime.datetime.now() 96 res = func(*args,**kwargs) # 执行传入的函数 97 return res 98 else: 99 print('账号密码不匹配') 100 continue 101 return wrapper 102 @login 103 def foo(): 104 print('hallo world') 105 @login 106 def fun(x,y,z): 107 time.sleep(2) 108 print(x+y+z) 109 @login 110 def func(x,y,z): 111 time.sleep(6) 112 print(x+y+z) 113 foo() 114 fun(1,2,3) 115 func(1,2,3)