Python 裝飾器是消除冗餘的強力工具。當你把功能模組化為大小合適的方法後,即使最複雜的工作流程,裝飾器也能讓它變得簡潔。
以 Django web 框架為例,處理請求的方法接收一個方法物件、回傳一個響應物件:
def handle_request(request):
return HttpResponse("Hello, World")
我最近遇到一個案例,需要寫幾個滿足下列條件的 API 方法:
作為一個註冊 API 端點的例子,一開始我會這樣寫:
def register(request):
result = None
# check for post only
if request.method != 'POST':
result = {"error": "this method only accepts posts!"}
else:
try:
user = User.objects.create_user(request.POST['username'],
request.POST['email'],
request.POST['password'])
# optional fields
for field in ['first_name', 'last_name']:
if field in request.POST:
setattr(user, field, request.POST[field])
user.save()
result = {"success": True}
except KeyError as e:
result = {"error": str(e) }
response = HttpResponse(json.dumps(result))
if "error" in result:
response.status_code = 500
return response
然而這樣每個 API 方法都得重寫 json 響應與錯誤返回的程式碼,造成大量邏輯重複。於是我們來用裝飾器落實 DRY 原則。
如果你不熟悉裝飾器,簡單說它就是有效的函式包裝器:Python 解釋器載入函式時便會執行包裝器,包裝器能修改函式的接收參數與回傳值。舉例來說,若我想讓某函式總是回傳比實際值大一的整數,可以這樣寫:
# a decorator receives the method it's wrapping as a variable 'f'
def increment(f):
# we use arbitrary args and keywords to
# ensure we grab all the input arguments.
def wrapped_f(*args, **kw):
# note we call f against the variables passed into the wrapper,
# and cast the result to an int and increment .
return int(f(*args, **kw)) + 1
return wrapped_f # the wrapped function gets returned.
接著就能用 @ 符號套用這個裝飾器:
@increment
def plus(a, b):
return a + b
result = plus(4, 6)
assert(result == 11, "We wrote our decorator wrong!")
裝飾器修改了既有函式,把回傳結果賦值給變數。此例中,'plus' 實際指向 increment(plus) 的結果。
現在把裝飾器應用到更實用的場景:在 Django 中若收到的不是 POST 請求,就用裝飾器回傳錯誤響應。
def post_only(f):
""" Ensures a method is post only """
def wrapped_f(request):
if request.method != "POST":
response = HttpResponse(json.dumps(
{"error": "this method only accepts posts!"}))
response.status_code = 500
return response
return f(request)
return wrapped_f
現在就能在註冊 API 上套用這個裝飾器:
@post_only
def register(request):
result = None
try:
user = User.objects.create_user(request.POST['username'],
request.POST['email'],
request.POST['password'])
# optional fields
for field in ['first_name', 'last_name']:
if field in request.POST:
setattr(user, field, request.POST[field])
user.save()
result = {"success": True}
except KeyError as e:
result = {"error": str(e) }
response = HttpResponse(json.dumps(result))
if "error" in result:
response.status_code = 500
return response
這樣我們就得到一個能在每個 API 方法中重複使用的裝飾器了。