Ask*_*ken 7 python flask flask-principal
我一直在看这篇文章:http: //pythonhosted.org/Flask-Principal/#granular-resource-protection
现在虽然它目前的工作方式没有任何问题,但我看不出它是非常实用的,因为在登录时所有帖子都被读取并且EditBlogPostNeed
被添加到身份中.
想象一下,如果我写的不仅仅是正常数量的帖子,那么从长远来看这不是一个非常好的策略,因为我想在访问视图时查看帖子/posts/<post_id>
.
有没有办法检查每个使用视图的请求Flask Principal
?
我当然可以通过懒惰的关系查询和过滤器轻松解决它,但我想使用Flask Principal
.
不确定我完全理解你的问题,但这可能会有所帮助。在 Flask 应用程序中,我使用 Flask-Principal 来获取管理员和编辑者等角色权限,并且还使用它来进行精细的资源保护,如Flask-Principal 文档中所述。就我而言,我正在检查用户是否有权访问特定帐户。在每个视图中都会加载身份并检查权限。
在视图中:
@login_required
def call_list(id, page=1):
dept = models.Department.query.get_or_404(id)
view_permission = auth.ViewAccountPermission(dept.office.account_id)
if view_permission.can():
# do something
Run Code Online (Sandbox Code Playgroud)
自定义权限:
ViewAccount = namedtuple('View', ['method', 'value'])
ViewAccountNeed = partial(ViewAccount, 'view')
class ViewAccountPermission(Permission):
def __init__(self, account_id):
need = ViewAccountNeed(unicode(account_id))
super(ViewAccountPermission, self).__init__(need)
Run Code Online (Sandbox Code Playgroud)
在身份加载器函数中:
if hasattr(current_user, 'assigned_accounts'):
for account_id in current_user.assigned_accounts():
identity.provides.add(auth.ViewAccountNeed(unicode(account_id)))
Run Code Online (Sandbox Code Playgroud)