day4
一:编写函数,(函数执行的时间是随机的)
import time
import random
def index():
fun = random.randint(1,10)
time.sleep(fun)
print('welcome index page')
index()
二:编写装饰器,为函数加上统计时间的功能
import time
import random
def timmer(func):
def inner():
start_time = time.time()
func()
stop_time = time.time()
print(stop_time-start_time)
return inner
@timmer
def index():
fun = random.randint(1,10)
time.sleep(fun)
print('welcome index page')
index()
三:编写装饰器,为函数加上认证的功能
(用户名egon 密码123)
import time
import random
def auth(func):
def inner(*args,**kwargs):
name = input('username>>:').strip()
pwd = input('password>>:').strip()
if name == 'egon' and pwd == '123':
print('login successfull')
res = func(*args,**kwargs)
return res
else:
print('username or password error,please enter again.')
return inner
def timmer(func):
def inner():
start_time = time.time()
func()
stop_time = time.time()
print(stop_time-start_time)
return inner
@auth
@timmer
def index():
fun = random.randint(1,10)
time.sleep(fun)
print('welcome index page')
index()
四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
(用户名egon 密码123)
import time
import random
status={'user':None,'login_status':False}
def auth(egine='file'):
def wrapper(func):
def inner(*args,**kwargs):
if status['user'] and status['login_status']:
res = func(*args,**kwargs)
return res
if egine == 'file':
with open('auth.json', mode='r', encoding='utf-8') as r_auth:
for line in r_auth:
user_dic = dict(eval(line))
name=user_dic['name']
password=user_dic['password']
elif egine == 'mysql':
pass
else:
pass
user_name = input('please enter username: ').strip()
user_passwd = input('please enter password: ').strip()
if user_name == name and user_passwd == password:
print('login successful')
status['user'] = user_name
status['login_status'] = True
res = func(*args, **kwargs)
return res
else:
print('username or password error,please enter again.')
return inner
return wrapper
def timmer(func):
def inner(*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 inner
@auth(egine='file')
@timmer
def index():
fun = random.randint(1,10)
time.sleep(fun)
print('welcome index page')
index()
@auth(egine='file')
@timmer
def home():
time.sleep(2)
print('welcome home page')
home()
五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
(用户名egon 密码123)
# import time
# import random
# status={'user':None,'login_status':False}
#
# def auth(egine='file'):
# def wrapper(func):
# def inner(*args,**kwargs):
# if status['user'] and status['login_status']:
# res = func(*args,**kwargs)
# return res
# if egine == 'file':
# with open('auth.json', mode='r', encoding='utf-8') as r_auth:
# for line in r_auth:
# user_dic = dict(eval(line))
# name = user_dic['name']
# password = user_dic['password']
# elif egine == 'mysql':
# pass
# else:
# pass
# user_name = input('please enter username: ').strip()
# user_passwd = input('please enter password: ').strip()
# if user_name == name and user_passwd == password:
# status['user'] = user_name
# status['login_status'] = True
# print('login successful')
# res = func(*args, **kwargs)
# return res
# else:
# print('username or password error,please enter again.')
# return inner
# return wrapper
#
# def timmer(func):
# def inner(*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 inner
#
# @auth(egine='file')
# @timmer
# def index():
# fun = random.randint(1,10)
# time.sleep(fun)
# print('welcome index page')
# index()
#
# @auth(egine='file')
# @timmer
# def home():
# time.sleep(2)
# print('welcome home page')
# home()
六:编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
from urllib.request import urlopen
def web_get(func):
def inner(*args,**kwargs):
url=func(*args,**kwargs)
web=urlopen(url).read()
print(web)
return web
return inner
@web_get
def url():
res=input("请您输入一个URL地址:")
return res
url()
七:为题目五编写装饰器,实现缓存网页内容的功能:
具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,
然后存到文件中扩展功能:用户可以选择缓存介质/缓存引擎,针对不同的url,缓存到不同的文件中
八:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,
然后在每个函数前加上装饰器,完成自动添加到字典的操作
九 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
注意:时间格式的获取
#import time
#time.strftime('%Y-%m-%d %X')
import time
def access_log(func):
def inner():
run_time = ("%s f1 run \n" %func())
with open("access.log","a",encoding="utf-8") as file:
file.write(run_time)
file.flush()
return run_time
return inner
def run_time(func):
def inner(*args,**kwargs):
start_time = time.strftime('%Y-%m-%d %X')
func(*args,**kwargs)
return start_time
return inner
@access_log
@run_time
def f1():
print("f1 service is starting.")
f1()

浙公网安备 33010602011771号