django - 如何检查@api_view函数的object_permissions?

标签 django django-rest-framework

我使用 @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

documentation说:

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/

相关文章:

python - 将 PrimaryKeyRelatedField 替换为另一个字段

python - Django(1.11) 休息框架在嵌套序列化器中发布 user.id

javascript - 您最喜欢在 Django 应用程序中测试 JavaScript 的方式是什么?

python - Django 新手很难使用模型和可重用的业务逻辑

django - 如何为默认的 Wagtail Page 实例使用 base.html?

python - Django Rest Framework——如何获取urls.py中的Http头信息

python - 努力让 django_comments 与 Django REST Framework 一起工作

python - 如何在自定义 Django 上传处理程序中逐行读取?

python - Django ModelForm 元数据

python - Django Rest Framework 外键嵌套