python - Flask Principal 粒度资源按需

标签 python flask flask-principal

我一直在看这篇文章: 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/

相关文章:

python - 使用 yocto 为 Raspberry pi 3 构建图像时出现解析错误

python - 在 Mac 上使用 pip 初始化安装的 PySpark 时出错

javascript - 将变量从js代码传递到db中的flask或类似的东西

twitter-bootstrap - React 无法与 Bootstrap 一起使用

python - Flask 登录和委托(delegate)人 - 即使我已登录,current_user 也是匿名的

使用 Docker 时找不到 Python 模块

Python 大型多列表高效查询

python - 将数据从 Flask 传递到 HTML

基于 Flask-Admin 角色的资源权限

python - Flask-Login & Flask-Principle 认证用户掉落到 flask_login.AnonymousUserMixin