13. Handler Decorators(裝飾器)
Sanic的視圖函數是十分簡單的python函數,開發者可以在模仿Flask框架的視圖函數使用裝飾器,請求鉤子就是典型的應用場景。
(1) 用戶認證裝飾器
假如開發者想要檢查登錄者的身份信息,開發者可以使用身份認證裝飾器進行簡單的檢查,並返回響應。
from functools import wraps from sanic.response import json
def authorized():
def decorator(f):
@wraps(f)
async def decorated_function(request, *args, **kwargs):
# run some method that checks the request
# for the client's authorization status
is_authorized = check_request_for_authorization_status(request)
if is_authorized:
# the user is authorized.
# run the handler method and return the response
response = await f(request, *args, **kwargs)
return response
else:
# the user is not authorized.
return json({'status': 'not_authorized'}, 403)
return decorated_function
return decorator
@app.route("/")
@authorized()
async def test(request):
return json({'status': 'authorized'})