方法如下:
from functools import update_wrapper
def owns_hotdog(hotdog):
def decorator(fn):
def wrapped_function(*args, **kwargs):
# First check if user is authenticated.
if not logged_in():
return redirect(url_for('login'))
# For authorization error it is better to return status code 403
# and handle it in errorhandler separately, because the user Could
# be already authenticated, but lack the privileges.
if not authorizeowner(hotdog):
abort(403)
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
@app.errorhandler(403)
def forbidden_403(exception):
return 'No hotdogs for you!', 403
当装饰器接受参数时,它实际上不是装饰器,而是返回 真正 装饰器的 工厂 函数。 __
但是,如果我是您,我将使用Flask-Login进行身份验证,并使用自定义装饰器和功能将其扩展,以处理授权。
我查看了Flask-Principal,但发现我的口味过于复杂。还没有检查过Flask-Security,但是我相信它使用Flask- Principal进行授权。总的来说,我认为大多数情况下,使用一些自定义代码的Flask-Login就足够了。