通过角色限制访问烧瓶视图某些区域的功能? [英] Restricting access to certain areas of a flask view function by role?
问题描述
我写了这个,看起来还不错:
I wrote this, which seems to work just fine:
@app.route('/admin', methods=['GET','POST'])
@login_required
def admin():
if not current_user.role == ROLE_ADMIN:
flash('You do not have access to view this page.')
return redirect(url_for('index'))
...the rest of my code...
由于我不想将这3行添加到我只希望对管理员可见的每个区域中而试图简化事情时,我尝试将其放在这样的函数中:
While trying to simplify things since I don't want to add these 3 lines to every area I want only visible to admins, I tried to put it in a function like so:
def admin_only():
if not current_user.role == ROLE_ADMIN:
flash('You do not have access to view this page.')
return redirect(url_for('index'))
然后放入我的视图功能:
and then put in my view function:
@app.route('/admin', methods=['GET','POST'])
@login_required
def admin():
admin_only()
...the rest of my code....
但是,这不符合我的预期.我收到了闪烁的消息,但是它没有像我想象的那样重定向.
However this doesn't work as I expected. I get the flashed message, but it does not redirect like I thought it would.
因此,有两个问题:
- 为什么返回的重定向无效?
- 是否有更好的方法来实现此功能?
推荐答案
实际回答您的问题.您应该使admin_only
函数成为装饰器,并装饰admin
视图方法.现在不重定向的原因是因为您没有从视图返回重定向.
To actually answer your question. You should make the admin_only
function a decorator and decorate the admin
view method. The reason it does not redirect now is because you are not returning the redirect from the view.
def admin():
ret = admin_only()
if( not ret ):
return ret
....
那应该可以解决您当前的问题,但这不是理想的选择,您希望将其功能转移到装饰器上.
That should fix your current issue, but it is not ideal and the functionality you wish should be moved to a decorator.
我还建议以下内容:
看看 Flask-Principal ,它可以为用户分配角色,然后进行限制根据这些角色对您的视图的访问权限.
Take a look at Flask-Principal it provides the ability to assign roles to users and then restrict access based on these roles to your views.
与Flask-Principal一起查看 Flask-Security ,因为它提供了许多与安全相关的有用信息Flask扩展名,并且使其更易于使用.
Along with Flask-Principal take a look at Flask-Security as it provides many useful security related Flask extensions and just makes it easier to use.
示例用法:
@roles_required( "admin" )
def website_control_panel():
return "Only Admin's can see this."
将仅 允许具有角色admin
附加到其帐户的用户.另一个用例是允许用户拥有许多角色,这些角色可以用roles_accepted
指定,并且可以按以下方式使用:
Will ONLY allow users with the role admin
attached to their account. Another use case is to allow a user to have one of many roles which can be specified with the roles_accepted
and can be used as following:
@roles_accepted( "journalist", "editor" )
def edit_paper():
return render_template( "paper_editor.html", ... )
仅允许将至少具有journalist
或editor
角色之一绑定到其帐户的用户.
Will only allow users that have at least one of the journalist
or editor
roles tied to their account.
这篇关于通过角色限制访问烧瓶视图某些区域的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!