Python__装饰器练习题,,一:编写函数,(函数


一:编写函数,(函数执行的时间是随机的)

 1 import time 2 def timmer(func): 3     def wrapper(*args,**kwargs): 4         start= time.time() 5         func(*args,**kwargs) 6         stop = time.time() 7         print(‘执行时间是%s‘%(stop-start)) 8      return wrapper 9 @timmer10 def exe():11     print(‘装饰器练习题!‘)12 exe()13 14 View Code

二:编写装饰器,为函数加上统计时间的功能

 1 import time 2 def timmer(func): 3     def wrapper(*args,**kwargs): 4         start= time.time() 5         func(*args,**kwargs) 6         stop = time.time() 7         print(‘执行时间是%s‘%(stop-start)) 8      return wrapper 9 @timmer10 def exe():11     print(‘你愁啥!‘)12 exe()13 14 View Code

三:编写装饰器,为函数加上认证的功能

 1 def auth(func): 2     def wrapper(*args,**kwargs): 3         name = input(‘请输入你的名字>>: ‘).strip() 4         password = input(‘请输入你的密码>>: ‘).strip() 5         if name == ‘egon‘ and password == ‘123‘: 6             func(*args,**kwargs) 7     return wrapper 8 @auth 9 def my_log(name):10     print(‘%s欢迎登陆‘%(name))11 my_log(‘egon‘)12 13 View Code

四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码

注意:从文件中读出字符串形式的字典,可以用eval(‘{“name”:”egon”,”password”:”123”}’)转成字典格式

 1 current_user = {‘name‘:None} 2 def auth(func): 3     def wrapper(*args,**kwargs): 4         if  current_user[‘name‘]: 5             func(*args, **kwargs) 6         else: 7             name = input(‘请输入你的用户名>>: ‘).strip() 8             password = input(‘请输入你的密码>>: ‘).strip() 9             with open(‘登录文件.txt‘,‘r‘,encoding = ‘utf-8‘) as f:10                 line = f.readline()11             my_dic = eval(line)12             if name == my_dic[‘name‘] and password == my_dic[‘password‘]:13                 func(*args,**kwargs)14                 current_user[‘name‘] = name15             else:16                 print(‘your input not exists‘)17      return wrapper18 @auth19 def my_log():20     print(‘this is my_log‘)21 @auth22 def my_name():23     print(‘欢迎登陆‘)24 my_log()25 my_name()26 27 View Code

五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录

 1 import time,random 2 user={‘user‘:None,‘login_time‘:None,‘timeout‘:0.000003,} 3 def timmer(func): 4     def wrapper(*args,**kwargs): 5         s1=time.time() 6         res=func(*args,**kwargs) 7         s2=time.time() 8         print(‘%s‘ %(s2-s1)) 9         return res10     return wrapper11 def auth(func):12     def wrapper(*args,**kwargs):13         if user[‘user‘]:14             timeout=time.time()-user[‘login_time‘]15             if timeout < user[‘timeout‘]:16                 return func(*args,**kwargs)17         name=input(‘name>>: ‘).strip()18         password=input(‘password>>: ‘).strip()19         if name == ‘egon‘ and password == ‘123‘:20             user[‘user‘]=name21             user[‘login_time‘]=time.time()22             res=func(*args,**kwargs)23             return res24     return wrapper25 @auth26 def index():27     time.sleep(random.randrange(3))28     print(‘welcome to index‘)29 @auth30 def home(name):31     time.sleep(random.randrange(3))32     print(‘welcome %s to home ‘ %name)33 34 index()35 home(‘egon‘)36 37 View Code

六:编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果

1 import requests2 def my_down(url = ‘https://www.baidu.com‘):3     def get():4         return requests.get(url).text5     return get6 baidu_web = my_down()7 print(baidu_web())8 9 View Code

七:为题目五编写装饰器,实现缓存网页内容的功能:

具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中

扩展功能:用户可以选择缓存介质/缓存引擎,针对不同的url,缓存到不同的文件中

 1 import requests 2 import os 3 cache_file=‘cache.txt‘ 4 def make_cache(func): 5     def wrapper(*args,**kwargs): 6         if not os.path.exists(cache_file): 7             with open(cache_file,‘w‘):pass 8  9         if os.path.getsize(cache_file):10             with open(cache_file,‘r‘,encoding=‘utf-8‘) as f:11                 res=f.read()12         else:13             res=func(*args,**kwargs)14             with open(cache_file,‘w‘,encoding=‘utf-8‘) as f:15                 f.write(res)16         return res17     return wrapper18 19 @make_cache20 def get(url):21     return requests.get(url).text22 23 View Code

八:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作

 1 route_dic={} 2  3 def make_route(name): 4     def deco(func): 5         route_dic[name]=func 6         return deco 7 @make_route(‘select‘) 8 def func1(): 9     print(‘select‘)10 11 @make_route(‘insert‘)12 def func2():13     print(‘insert‘)14 15 @make_route(‘update‘)16 def func3():17     print(‘update‘)18 19 @make_route(‘delete‘)20 def func4():21     print(‘delete‘)22 23 print(route_dic)24 25 View Code

九 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定

注意:时间格式的获取

import time

time.strftime(‘%Y-%m-%d %X’)

 1 import time,os 2 def auth(logfile): 3     def deco(func): 4         if not os.path.exists(logfile): 5             with open(logfile,‘w‘,encoding = ‘utf-8‘) as f: 6                 pass 7         def wrapper(*args,**kwargs): 8             res = func(*args,**kwargs) 9             with open(logfile,‘a‘,encoding = ‘utf-8‘) as f:10                 f.write(‘%s %s run‘%(time.strftime(‘%Y-%m-%d %X‘),func.__name__))11         return wrapper12     return deco13 @auth(‘suhao.txt‘)14 def index():15     print(‘this is my index‘)16 index()17 18 View Code

Python__装饰器练习题

评论关闭