Python裝飾器實(shí)現(xiàn)方法及應(yīng)用場(chǎng)景詳解
應(yīng)用場(chǎng)景:
1、授權(quán)(Authorization)
裝飾器能有助于檢查某個(gè)人是否被授權(quán)去使用一個(gè)web應(yīng)用的端點(diǎn)(endpoint)。它們被大量使用于Flask和Django web框架中。這里是一個(gè)例子來(lái)使用基于裝飾器的授權(quán):
from functools import wraps # 最新版python引用是 import functoolsdef requires_auth(f): # f 就是我們需要裝飾的函數(shù),一看就是不帶參數(shù)的裝飾器 @wraps(f) # 新版python寫法 @functools.wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): authenticate() return f(*args, **kwargs) return decorated # 該裝飾器需相關(guān)配置才能運(yùn)行,這里是截取代碼展示應(yīng)用
2.、日志(Logging)
日志是裝飾器運(yùn)用的另一個(gè)亮點(diǎn)。這是個(gè)例子:
from functools import wrapsdef logit(func): @wraps(func) def with_logging(*args, **kwargs): print(func.__name__ + ' was called') return func(*args, **kwargs) return with_logging@logitdef addition_func(x): '''Do some math.''' return x + xresult = addition_func(4)
我敢肯定你已經(jīng)在思考裝飾器的一個(gè)其他聰明用法了。
3.、帶參數(shù)的裝飾器
帶參數(shù)的裝飾器是典型的閉包函數(shù)
4.、在函數(shù)中嵌入裝飾器
我們回到日志的例子,并創(chuàng)建一個(gè)包裹函數(shù),能讓我們指定一個(gè)用于輸出的日志文件
from functools import wrapsdef logit(logfile=’out.log’): def logging_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): log_string = func.__name__ + ' was called' print(log_string) # 打開(kāi)logfile,并寫入內(nèi)容 with open(logfile, ’a’) as opened_file:# 現(xiàn)在將日志打到指定的logfileopened_file.write(log_string + ’n’) return func(*args, **kwargs) return wrapped_function return logging_decorator@logit()def myfunc1(): passmyfunc1()# Output: myfunc1 was called# 現(xiàn)在一個(gè)叫做 out.log 的文件出現(xiàn)了,里面的內(nèi)容就是上面的字符串@logit(logfile=’func2.log’)def myfunc2(): passmyfunc2()# Output: myfunc2 was called# 現(xiàn)在一個(gè)叫做 func2.log 的文件出現(xiàn)了,里面的內(nèi)容就是上面的字符串
5.、裝飾器類
現(xiàn)在我們有了能用于正式環(huán)境的logit裝飾器,但當(dāng)我們的應(yīng)用的某些部分還比較脆弱時(shí),異常也許是需要更緊急關(guān)注的事情。比方說(shuō)有時(shí)你只想打日志到一個(gè)文件。而有時(shí)你想把引起你注意的問(wèn)題發(fā)送到一個(gè)email,同時(shí)也保留日志,留個(gè)記錄。這是一個(gè)使用繼承的場(chǎng)景,但目前為止我們只看到過(guò)用來(lái)構(gòu)建裝飾器的函數(shù)。
幸運(yùn)的是,類也可以用來(lái)構(gòu)建裝飾器。那我們現(xiàn)在以一個(gè)類而不是一個(gè)函數(shù)的方式,來(lái)重新構(gòu)建logit。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IntelliJ IDEA安裝插件的方法步驟2. ASP.NET MVC使用typeahead.js實(shí)現(xiàn)輸入智能提示功能3. html小技巧之td,div標(biāo)簽里內(nèi)容不換行4. Intellij IDEA連接Navicat數(shù)據(jù)庫(kù)的方法5. 如何通過(guò)axios發(fā)起Ajax請(qǐng)求(最新推薦)6. php框架知識(shí)點(diǎn)的整理和補(bǔ)充7. php過(guò)濾器使用詳解8. 選擇模式 - XSL教程 - 29. 在vue中使用image-webpack-loader實(shí)例10. Python實(shí)現(xiàn)圖片指定位置加圖片水印(附Pyinstaller打包exe)
