我使用 @api_view
装饰器定义了一个 View 函数。现在我想测试该对象中的对象级权限。
我知道有一个 check_object_permissions
可以让我检查我在 View 上定义的权限,但我不知道如何调用它。该文档提供了类的示例,而不是函数的示例。
@api_view(["GET"])
@permission_classes([IsAuthenticated & IsOwnerOfItem])
def query_something_related_to_items(request, item_id):
item = get_object_or_404(Item, id=item_id)
# I want to test IsOwnerOfItem here,
# I guess I need to call something like:
# "self".check_object_permissions(request, item)
# custom code here
return something
class IsOwnerOfItem(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return obj.owner == request.user
If you're writing your own views and want to enforce object level permissions, or if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object.
但是如何在 View 函数中调用它呢?
最佳答案
您提到的部分文档说:
Object level permissions are run by REST framework's generic views when .get_object()
因此,基于类的 View 就在那里。为了在基于函数的 View 中检查对象权限,您应该编写逻辑并在您决定 request
不应访问 item
时引发 PermissionDenied
。伪代码:
from rest_framework.exceptions import PermissionDenied
# I want to test IsOwnerOfItem here,
# I guess I need to call something like:
# `has_permission_for_item` is your own function
if not has_permission_for_item(request, item):
raise PermissionDenied()
关于django - 如何检查@api_view函数的object_permissions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67057773/