flask-security roles_required 具有可插入视图

flask-security roles_required with pluggable views

我正在尝试要求角色访问我定义为 MethodView 的视图。但是,我似乎无法正确命名路由。

如果我只需要使用装饰器登录,一切正常:

activities = Blueprint("activities", __name__, url_prefix="/activities")

class ActivitiesView(MethodView):
    def get():
        pass

    def post():
        pass

view = login_required(ActivitiesView.as_view("activities"))
activities.add_url_rule('/', view_func=view)

我得到了所需的路线名称,即 activities.activities:

>>> current_app.url_map
Map([...
 <Rule '/activities/' (HEAD, POST, OPTIONS, GET) -> activities.activities>,
...])

但是,当我尝试使用 roles_required 时,路由名称被破坏并且不再列出 POST 方法:

view = roles_required("experimenter", ActivitiesView.as_view("activities"))
activities.add_url_rule('/', view_func=view)

>>> current_app.url_map
Map([...
 <Rule '/activities/' (HEAD, OPTIONS, GET) -> activities.wrapper>,
...])

将参数切换为 add_url_rule 不会改变任何内容。如何使用 roles_required 而不会弄乱路由名称?

这样做会修复路由名称,但不会修复缺少的 POST 方法:

view = roles_required("experimenter", endpoint="activities", ActivitiesView.as_view("activities"))
activities.add_url_rule('/', view_func=view)

解决方法是调用装饰器:

view = roles_required("experimenter")(ActivitiesView.as_view("activities"))
activities.add_url_rule('/', view_func=view)

或者:

decorators = [roles_required("experimenter")]

感谢这篇文章:

http://scottlobdell.me/2015/04/decorators-arguments-python/