因为Sanic处理函数就是普通的 Python 函数,所以我们可以想 Flask 那样对它们使用修饰器。比较典型的应用场景是,我们希望在运行处理函数之前执行一些代码。
授权修饰器
web应用中经常需要特定用户权限才能访问某些路径。我们可以创建修饰器来包装处理函数,检查一个请求的客户端是否被授权访问,,并返回适当的响应。
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'})
用户授权检查是处理函数修饰器应用的一个典型场景,任何需要用户授权的路由节点都可以使用该修饰器进行修饰。
这个功能也可以通过 Sanic 中间件 来实现,感兴趣的同学可以尝试用中间件来实现授权检查。

我的公众号:猿人学 Python 上会分享更多心得体会,敬请关注。
***版权申明:若没有特殊说明,文章皆是猿人学 yuanrenxue.con 原创,没有猿人学授权,请勿以任何形式转载。***
说点什么吧...