处理装饰器

由于 Sanic 处理程序是简单的 Python 函数,你可以用类似 Flask 的方法用装饰器包裹他们。一个经典的用例就是当你想要在处理程序的代码执行前先运行一些代码。

认证装饰器

假设你想要检查一个用户是否被授权去访问特定端点。你可以创建一个装饰器来包裹一个处理程序,检查一个请求是否客户端被授权去访问一个资源,并且发送一个合理的响应。

  1. from functools import wraps
  2. from sanic.response import json
  3. def authorized():
  4. def decorator(f):
  5. @wraps(f)
  6. async def decorated_function(request, *args, **kwargs):
  7. # run some method that checks the request
  8. # for the client's authorization status
  9. is_authorized = check_request_for_authorization_status(request)
  10. if is_authorized:
  11. # the user is authorized.
  12. # run the handler method and return the response
  13. response = await f(request, *args, **kwargs)
  14. return response
  15. else:
  16. # the user is not authorized.
  17. return json({'status': 'not_authorized'}, 403)
  18. return decorated_function
  19. return decorator
  20. @app.route("/")
  21. @authorized()
  22. async def test(request):
  23. return json({status: 'authorized'})