作业day14
2020-06-18
一:编写函数,(函数执行的时间用time.sleep(n)模拟)
import time def index(x, n): print(x, 'from func') time.sleep(n) return 111
二:编写装饰器,为函数加上统计时间的功能
import time def outer1(func): def wrapper(*args, **kwargs): start_time = time.time() res = func(*args, **kwargs) end_time = time.time() print('Running time is %s' % (end_time - start_time)) return res return wrapper index = outer1(index)
三:编写装饰器,为函数加上认证的功能
def outer2(func): def wrapper(*args, **kwargs): inp_name = input("请输入您的用户名:").strip() inp_pwd = input("请输入您的密码:").strip() if inp_name == "jason" and inp_pwd == "123": print("认证成功!") res = func(*args, **kwargs) return res else: print("用户名或密码错误,认证失败!") return wrapper index = outer2(index)
四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
user_login = "" def outer3(func): def wrapper(*args, **kwargs): while user_login == "": inp_name = input("请输入您的用户名:").strip() inp_pwd = input("请输入您的密码:").strip() with open('registration.txt', mode='r', encoding='utf-8') as f: for line in f: if inp_name == eval(line)['name'] and inp_pwd == eval(line)['pwd']: # 假设文件中用户信息以字典形式的字符串存放 print('login successfully!') global user_login user_login = inp_name else: print("login failure") res = func(*args, **kwargs) return res return wrapper @outer3 def login(): pass @outer3 def transfer(): pass @outer3 def withdraw(): pass
五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
import time from functools import wraps user_login = "" def outer4(func): @wraps(func) def wrapper(*args, **kwargs): while user_login == "": inp_name = input("请输入您的用户名:").strip() inp_pwd = input("请输入您的密码:").strip() with open('registration.txt', mode='r', encoding='utf-8') as f: for line in f: if inp_name == eval(line)['name'] and inp_pwd == eval(line)['pwd']: # 假设文件中用户信息以字典形式的字符串存放 print('login successfully!') global user_login user_login = inp_name else: print("login failure") login_time = time.time() res = func(*args, **kwargs) # 未完待续 return res return wrapper
六:编写装饰器,为多个函数加上记录日志的功能:函数一旦运行则按照下述格式记录日志
函数开始执行的时间 函数名 返回值
2020-06-18 12:13:38 index 456
2020-06-18 12:13:39 home 123
提示:
统计时间time.strftime('%Y-%m-%d %H:%M:%S')
函数名func.__name__
import time from functools import wraps def outer6(func): @wraps(func) def wrapper(*args, **kwargs): res = func(*args, **kwargs) with open('access.log', mode='a', encoding='utf-8') as f: print('%s %s %s\n' % (time.strftime('%Y-%m-%d %H-%M-%S'), func.__name__, res)) return res return wrapper