作业3.21

一:编写函数,(函数执行的时间用time.sleep(n)模拟)
def timer():
start_time = time.time()
time.sleep(3)
stop_time = time.time()
use_time = stop_time - start_time
print(use_time)

二:编写装饰器,为函数加上统计时间的功能
def outer(func):
def timer(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
stop_time = time.time()
use_time = stop_time - start_time
print(use_time)
return res

return timer
def func():
print(10)
func()
三:编写装饰器,为函数加上认证的功能
def auth(func):
def inter(*args, **kwargs):
while True:
name = input("请输入用户名:").strip()
with open("use.txt",'r',encoding='utf-8') as f:
for line in f:
user_name,user_pwd = line.strip().split("-")
if name == user_name:
while True:
pwd = input("请输入密码:").strip()
if pwd == user_pwd:
print("欢迎登陆。")
res = func(*args,**kwargs)
return res
else:
print("该用户不存在。")

return inter


@auth
def foo():
   print(“
请先验证”)
四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码,
在超时时间内无需重复登录,超过了超时时间,则必须重新登录。

注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
def time_count(func):
def hide(*args, **kwargs):
star = time.time()
func(*args, **kwargs)
end = time.time()
print('本程序执行耗时{}秒'.format(end - star))

return hide


def login_check_1(func):
def hide(*args, **kwargs):
count = 1
while count:
login_name = input('输入登录账号:').strip()
login_pwd = input('输入登录密码:').strip()
with open(r'user.txt', mode='rt', encoding='utf-8')as f:
for check_info in f:
check_list = check_info.strip().split(':')
if login_name == check_list[0] and login_pwd == check_list[1]:
print('===登录成功,后续程序将继续执行===')
count = 0
break
else:
print('用户名或密码错误,重新输入')
func(*args, **kwargs)

return hide


def login_check_2(func):
def hide(*args, **kwargs):
tag = 1
while tag:
login_name = input('输入登录账号:').strip()
login_pwd = input('输入登录密码:').strip()
with open(r'02 账号库.txt', mode='rt', encoding='utf-8')as file:
for check_info in file:
check_list = check_info.strip().split(':')
if login_name == check_list[0] and login_pwd == check_list[1]:
print('===登录成功,后续程序将继续执行===')
login_star_time = time.time()
func(*args, **kwargs)
input('模拟操作时间')
login_end_time = time.time()
do_time = login_end_time - login_star_time
if do_time < 6:
tag = 0
else:
print('操作超时,重新登录')
break
else:
print('用户名或密码错误,重新输入')

return hide


def add(a, b):
time.sleep(1)
print('功能:{}'.format(a + b))


posted @ 2020-03-23 19:55  小小码农梦还家  阅读(101)  评论(0编辑  收藏  举报