一:编写函数,(函数执行的时间用time.sleep(n)模拟)
import time
def index(a, b):
num = a + b
time.sleep(6)
print(num)
return num
二:编写装饰器,为函数加上统计时间的功能
def timer(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
index = timer(index)
index(1,2)
'''
输出结果(结合一+二题)
3
run time is 6.0002734661102295
'''
三:编写装饰器,为函数加上认证的功能
def login(func):
def wrapper(*args,**kwargs):
user_name = input('请输入用户名:')
user_pwd = input('请输入密码:')
with open('db.txt',mode='r',encoding='utf-8') as f:
login = {}
for line in f:
name, pwd = line.strip().split(':')
login[name] = user_pwd
if user_name in login and user_pwd == login[name]:
print('登录成功!')
elif user_name not in login:
print('用户名不存在!')
else:
print('密码错误!')
return wrapper
index = login(index)
index(1,2)
四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
db = 'db.txt'
login_status = {'user': None, 'status': False}
def auth(auth_type='file'):
def auth2(func):
def wrapper(*args, **kwargs):
if login_status['user'] and login_status['status']:
return func(*args, **kwargs)
if auth_type == 'file':
with open(db, encoding='utf-8') as f:
dic = eval(f.read())
name = input('username: ').strip()
password = input('password: ').strip()
if name in dic and password == dic[name]:
login_status['user'] = name
login_status['status'] = True
res = func(*args, **kwargs)
return res
else:
print('username or password error')
elif auth_type == 'sql':
pass
else:
pass
return wrapper
return auth2
@auth()
def index():
print('index')
@auth(auth_type='file')
def home(name):
print('welcome %s to home' % name)
index()
home('egon')
五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
import time,random
user = {'user': None, 'login_time': None, 'timeout': 0.000003, }
def timer(func):
def wrapper(*args, **kwargs):
s1 = time.time()
res = func(*args, **kwargs)
s2=time.time()
print('%s' % (s2-s1))
return res
return wrapper
def auth(func):
def wrapper(*args, **kwargs):
if user['user']:
timeout = time.time()-user['login_time']
if timeout < user['timeout']:
return func(*args, **kwargs)
name = input('name>>: ').strip()
password = input('password>>: ').strip()
if name == 'egon' and password == '123':
user['user'] = name
user['login_time'] = time.time()
res = func(*args, **kwargs)
return res
return wrapper
@auth
def index():
time.sleep(random.randrange(3))
print('welcome to index')
@auth
def home(name):
time.sleep(random.randrange(3))
print('welcome %s to home ' % name)
index()
home('egon')
六:选做题
# 思考题(选做),叠加多个装饰器,加载顺序与运行顺序,可以将上述实现的装饰器叠加起来自己验证一下
# @deco1 # index=deco1(deco2.wrapper的内存地址)
# @deco2 # deco2.wrapper的内存地址=deco2(deco3.wrapper的内存地址)
# @deco3 # deco3.wrapper的内存地址=deco3(index)
# def index():
# pass
@timer
@auth
def index(x, y):
num = x + y
time.sleep(5)
print(num)
return num
index(1,2)
index(2,3)
index(3,4)