一:編寫函數,(函數執行的時間是隨機的)
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 @timmer
10 def exe():
11 print('你愁啥!')
12 exe()
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 @timmer
10 def exe():
11 print('你愁啥!')
12 exe()
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')
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'] = name
15 else:
16 print('your input not exists')
17 return wrapper
18 @auth
19 def my_log():
20 print('this is my_log')
21 @auth
22 def my_name():
23 print('歡迎登陸')
24 my_log()
25 my_name()
View Code
五:編寫裝飾器,為多個函數加上認證功能,要求登錄成功一次,在超時時間內無需重復登錄,超過了超時時間,則必須重新登錄
1 import time,random
2 user={'user':None,'login_time':None,'timeout':0.000003,}
3
4 def timmer(func):
5 def wrapper(*args,**kwargs):
6 s1=time.time()
7 res=func(*args,**kwargs)
8 s2=time.time()
9 print('%s' %(s2-s1))
10 return res
11 return wrapper
12
13
14 def auth(func):
15 def wrapper(*args,**kwargs):
16 if user['user']:
17 timeout=time.time()-user['login_time']
18 if timeout < user['timeout']:
19 return func(*args,**kwargs)
20 name=input('name>>: ').strip()
21 password=input('password>>: ').strip()
22 if name == 'egon' and password == '123':
23 user['user']=name
24 user['login_time']=time.time()
25 res=func(*args,**kwargs)
26 return res
27 return wrapper
28
29 @auth
30 def index():
31 time.sleep(random.randrange(3))
32 print('welcome to index')
33
34 @auth
35 def home(name):
36 time.sleep(random.randrange(3))
37 print('welcome %s to home ' %name)
38
39 index()
40 home('egon')
View Code
六:編寫下載網頁內容的函數,要求功能是:用戶傳入一個url,函數返回下載頁面的結果
1 import requests
2 def my_down(url = 'https://www.baidu.com'):
3 def get():
4 return requests.get(url).text
5 return get
6 baidu_web = my_down()
7 print(baidu_web())
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 res
17 return wrapper
18
19 @make_cache
20 def get(url):
21 return requests.get(url).text
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)
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 wrapper
12 return deco
13 @auth('suhao.txt')
14 def index():
15 print('this is my index')
16 index()
View Code