我试图要求角色访问我已定义为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)
答案 0 :(得分:1)
解决方法是调用装饰器:
view = roles_required("experimenter")(ActivitiesView.as_view("activities"))
activities.add_url_rule('/', view_func=view)
可替换地:
decorators = [roles_required("experimenter")]
感谢这篇文章: