一:编写函数,(函数执行的时间用time.sleep(n)模拟)
import time
def index():
time.sleep(3)
print('hello world')
index()
# 二:编写装饰器,为函数加上统计时间的功能
import time
def timmer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
stop_time = time.time()
print("run time is :%s" % (stop_time - start_time))
return res
return wrapper
@timmer
def index():
time.sleep(3)
print('hello world')
index()
三:编写装饰器,为函数加上认证的功能
def auth(func):
def wrapper(*args, **kwargs):
count = 0
while count < 3:
with open('a.txt', mode='rt', encoding='utf-8')as f:
for line in f:
name, pwd = line.strip().split('😂
if inp_name == name and inp_pwd == pwd:
print('认证成功')
res = func(*args, **kwargs)
return res
count=4
else:
print('认证失败')
count += 1
return wrapper
@auth
def index():
time.sleep(3)
print('hello world')
return 1
index()
四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
def login(func):
def wrapper(*args, **kwargs):
count = 0
while count < 3:
with open('a.txt', mode='rt', encoding='utf-8')as f:
for line in f:
name, pwd = line.strip().split('😂
if inp_name == name and inp_pwd == pwd:
print('认证成功')
res = func(*args, **kwargs)
return res
count=4
else:
print('认证失败')
count += 1
return wrapper
@login
def index():
time.sleep(3)
print('hello world')
return 1
login()
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
六:编写装饰器,为多个函数加上记录日志的功能:函数一旦运行则按照下述格式记录日志
函数开始执行的时间 函数名 返回值
2020-06-18 12:13:38 index 456
2020-06-18 12:13:39 home 123
import time
def log_path(func):
def wrapper(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
stop_time = time.time()
with open("a.txt", mode="a", encoding="utf-8")as f1:
f1.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} {a.name} {res}")
return res
return wrapper
@log_path
def index():
print('hello world')
return 456
index()
提示:
统计时间time.strftime('%Y-%m-%d %H:%M:%S')
函数名func.name