裝飾器是 Python 進階開發的核心技能,常見於 Web 框架路由(@app.route)、權限驗證、效能分析等場景。本文透過一個「三層網頁爬取、需快取避免重複請求」的實戰案例,展示如何設計帶參數的裝飾器實現「引數級快取」,大幅降低網路開銷並支援斷點續傳。
核心邏輯:以函式名 + 呼叫引數(序列化後 MD5)為 Key,將回傳值序列化存檔。再次呼叫時若快取存在直接讀取,否則執行原函式並寫入快取。
import os
import hashlib
def deco_args_recent_cache(category='dumps'):
'''帶參數裝飾器:category 用於隔離不同業務的快取目錄'''
def deco_recent_cache(func):
def func_wrapper(*args, **kargs):
sig = _mk_cache_sig(*args, **kargs)
data = _get_recent_cache(category, func.__name__, sig)
if data is not None:
return data # 命中快取,直接返回
data = func(*args, **kargs) # 未命中,執行原函式
if data is not None:
_set_recent_cache(category, func.__name__, sig, data)
return data
return func_wrapper
return deco_recent_cache
def _mk_cache_sig(*args, **kargs):
'''引數序列化 → MD5,作為唯一快取鍵'''
src_data = repr(args) + repr(kargs)
return hashlib.md5(src_data.encode()).hexdigest()
def _get_recent_cache(category, func_name, sig):
path = f'{category}/{func_name}/{sig}'
if os.path.isfile(path):
with open(path, 'r') as f:
return eval(f.read()) # 簡單場景用 eval,生產建議 json/pickle
return None
def _set_recent_cache(category, func_name, sig, data):
dir_path = f'{category}/{func_name}'
os.makedirs(dir_path, exist_ok=True)
path = f'{dir_path}/{sig}'
with open(path, 'w') as f:
f.write(repr(data))
@deco_args_recent_cache()
def func_top(url):
data_dict = {}
sub_urls = fetch_sub_urls(url) # 取得子頁面 URL 列表
data_list = [func_sub(u) for u in sub_urls]
data_dict['data'] = data_list
return data_dict
@deco_args_recent_cache()
def func_sub(url):
data_dict = {}
bottom_urls = fetch_bottom_urls(url)
data_list = [func_bottom(u) for u in bottom_urls]
data_dict['data'] = data_list
return data_dict
@deco_args_recent_cache()
def func_bottom(url):
return fetch_data(url) # 真正的網路請求
eval/repr 替換為 json 或 pickle,支援更複雜資料結構並提升安全性。tempfile.gettempdir() 或配置化路徑。fcntl/portalocker)防止寫衝突。這個模式不僅適用於爬蟲,任何「純函式、輸入決定輸出、執行成本高」的場景(如 API 呼叫、複雜計算、資料庫查詢)都能直接套用,是 Python 開發者工具箱裡的利器。