您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Flask中使用参数制作python装饰器函数(用于授权)

如何在Flask中使用参数制作python装饰器函数(用于授权)

方法如下:

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就足够了。

Python 2022/1/1 18:29:11 有349人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶