我一直在看这篇文章: http://pythonhosted.org/Flask-Principal/#granular-resource-protection
现在虽然它当前的工作方式没有任何问题,但我看不出它非常有用,因为在登录时所有帖子都被读取并且 EditBlogPostNeed
被添加到标识中。
想象一下,如果我写的帖子数量超过了正常数量,从长远来看,这将不是一个很好的策略,因为我想在访问 View 时查看帖子 /posts/<post_id>
.
有没有办法使用 Flask Principal
对 View 的每个请求执行此检查? ?
我当然可以通过惰性关系查询和过滤器轻松绕过它,但我想使用 Flask Principal
.
最佳答案
不确定我是否完全理解您的问题,但这可能会有所帮助。在 Flask 应用程序中,我使用 Flask-Principal 来获得管理员和编辑器等角色权限,并且我还使用它来进行粒度资源保护,如 Flask-Principal docs 中所述。 .就我而言,我正在检查用户是否有权访问特定帐户。在每个 View 中加载身份并检查权限。
在 View 中:
@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
自定义权限:
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)
在身份加载函数中:
if hasattr(current_user, 'assigned_accounts'):
for account_id in current_user.assigned_accounts():
identity.provides.add(auth.ViewAccountNeed(unicode(account_id)))
关于python - Flask Principal 粒度资源按需,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18319487/