本文整理汇总了Python中rest_framework.permissions.DjangoObjectPermissions方法的典型用法代码示例。如果您正苦于以下问题:Python permissions.DjangoObjectPermissions方法的具体用法?Python permissions.DjangoObjectPermissions怎么用?Python permissions.DjangoObjectPermissions使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.permissions
的用法示例。
在下文中一共展示了permissions.DjangoObjectPermissions方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_viewset_get_queryset_with_DjangoObjectPermissions_permission
# 需要导入模块: from rest_framework import permissions [as 别名]
# 或者: from rest_framework.permissions import DjangoObjectPermissions [as 别名]
def test_viewset_get_queryset_with_DjangoObjectPermissions_permission(self):
from rest_framework.permissions import DjangoObjectPermissions
setattr(self.view, "permission_classes", (DjangoObjectPermissions,))
# The `DjangoObjectPermissions` is a subclass of `DjangoModelPermissions` and
# therefore unsupported.
request = factory.get(path="/", data="", content_type="application/json")
try:
self.view.as_view(actions={"get": "list"})(request)
self.fail("Did not fail with AssertionError when calling HaystackView with DjangoModelPermissions")
except (AttributeError, AssertionError) as e:
if isinstance(e, AttributeError):
self.assertEqual(str(e), "'SearchQuerySet' object has no attribute 'model'")
else:
self.assertEqual(str(e), "Cannot apply DjangoModelPermissions on a view that does "
"not have `.model` or `.queryset` property.")
示例2: has_object_permission
# 需要导入模块: from rest_framework import permissions [as 别名]
# 或者: from rest_framework.permissions import DjangoObjectPermissions [as 别名]
def has_object_permission(self, request, view, obj):
"""Check object permissions."""
# admins can do anything
if request.user.is_superuser:
return True
# `share` permission is required for editing permissions
if "permissions" in view.action:
self.perms_map["POST"] = ["%(app_label)s.share_%(model_name)s"]
if view.action in ["add_data", "remove_data"]:
self.perms_map["POST"] = ["%(app_label)s.add_%(model_name)s"]
if hasattr(view, "get_queryset"):
queryset = view.get_queryset()
else:
queryset = getattr(view, "queryset", None)
assert queryset is not None, (
"Cannot apply DjangoObjectPermissions on a view that "
"does not set `.queryset` or have a `.get_queryset()` method."
)
model_cls = queryset.model
user = request.user
perms = self.get_required_object_permissions(request.method, model_cls)
if not user.has_perms(perms, obj) and not AnonymousUser().has_perms(perms, obj):
# If the user does not have permissions we need to determine if
# they have read permissions to see 403, or not, and simply see
# a 404 response.
if request.method in permissions.SAFE_METHODS:
# Read permissions already checked and failed, no need
# to make another lookup.
raise Http404
read_perms = self.get_required_object_permissions("GET", model_cls)
if not user.has_perms(read_perms, obj):
raise Http404
# Has read permissions.
return False
return True