如何在Django Rest Framework中返回403错误的数据?

时间:2014-09-15 18:34:40

标签: python django django-rest-framework

当GET请求转到/obj/1

的API后端时

我检查自定义权限类以查看用户是否有权访问,如果没有,则返回403。

但是,我想附加对象ID,以便用户可以单击前端的按钮来请求访问。

我目前的实现是覆盖retrieve方法和"手动"检查那里的许可。

简化权限

class CustomPerm(...):
    def has_object_permission(...):
        return request.user.is_staff

视图集

class CustomViewSet(...):
    model = Model
    permission_classes = (CustomPerm, )

    def retrieve(self, request, pk=None):
        obj = get_object_or_404(Model, pk=pk)

        has_perm = CustomPerm().has_object_permission(request, self, obj=obj)
        if not has_perm:
            data = { 'id': obj.id }
            return Response(data, status=403)

        return super(ModelViewSet, self).retrieve(request, pk=pk)

因此,我当前的方法has_perm返回用户的QuerySet,而不是权限方法中定义的布尔值。怎么样?

对此有更清洁的方法吗?

1 个答案:

答案 0 :(得分:22)

from rest_framework import permissions
from rest_framework.exceptions import PermissionDenied

class CustomPerm(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.user.is_staff:
            return True
        raise PermissionDenied({"message":"You don't have permission to access",
                                "object_id": obj.id})

您无需覆盖检索方法

class CustomViewSet(...):
    model = Model
    permission_classes = (CustomPerm, )