django的跨多个模型的对象级权限。
olp的Python项目详细描述
对象级权限(OLP)
django从django 1.2开始就支持对象级权限,但是 需要自定义身份验证后端来实现它。有 tons of implementations 但大多数都是为了处理特定的情况。
功能
与大多数其他实现一样,olp意味着要处理一些特定的情况 我们遇到了。
不同类型的“组”
django有一个“用户”和“组”的概念,认证系统 是建立在。这些组仅由单个模型组成,不能 建立在不同的,不同的类型之上。olp允许您有多个 模型有助于单个用户的权限,甚至在对象上 水平。
不同的模型可以有独立的权限,而不需要 直接附加到用户的。如果它们附加到用户(并指定 在设置中),它们可以对用户的总体权限做出贡献。
直接积分
olp直接与django的身份验证后端集成。当它 不需要使用olp,建议使用它,因为它更易于使用 奥尔普。
方法规范化
只有用户和组模型具有has_perm功能,这将成为 使用其他型号时的快速限制。olp修补另一个 模型(在设置中指定)并为它们提供has_perm方法 它们的行为与给用户和组的相同。
为了使分配和删除权限与检查权限一样简单, olp还将用assign_perm和^{tt3}修补所有模型$ 方法。
设置
olp使用键确定django设置文件中的设置 OLP_SETTINGS。这必须是包含键models的字典, 如下所示。
OLP_SETTINGS={"models":(),}
models键应包含包含字符串路径的元组的元组 到用于由用户筛选的模型和queryset筛选器。
示例
示例/settings.py
OLP_SETTINGS={"models":(("django.contrib.auth.models.Group","users"),),}
示例/models.py
fromdjango.dbimportmodelsclassApple(models.Model):owner=models.ForeignKey("auth.User")classMeta:permissions=(("can_see_apple","User can see the apple."),)
python外壳
>>>fromolp.utilsimportpatch_models>>>patch_models()>>>fromexample.modelsimportApple>>>fromdjango.contrib.authimportGroup,User>>>user=User.objects.all()[0]>>>group=Group.objects.all()[0]>>>apple=Apple(owner=user)>>>apple.save()>>>user.has_perm("example.can_see_apple",apple)False>>>user.assign_perm("can_see_apple",apple)True>>>user.has_perm("example.can_see_apple",apple)True>>>user.remove_perm("example.can_see_apple",apple)True>>>user.has_perm("example.can_see_apple",apple)False>>>group.has_perm("example.can_see_apple",apple)False>>>group.assign_perm("example.can_see_apple",apple)True>>>group.has_perm("example.can_see_apple",apple)True>>>user.has_perm("example.can_see_apple",apple)True