Django REST框架 - 如何返回404错误而不是403

时间:2018-02-21 10:18:03

标签: python django django-rest-framework

只有在用户通过身份验证并满足某些其他条件时,我的API才允许对某些对象进行访问(任何请求)。

class SomethingViewSet(viewsets.ModelViewSet):
    queryset = Something.objects.filter(query_hiding_non_authorized_objects)
    serializer_class = SomethingSerializer

    permission_classes = (permissions.IsAuthenticated, SomePermission)

但是,如果用户尝试查看未授权的对象,则DRF返回403错误,这表示存在具有所请求的id的对象。在这些情况下如何返回404错误?

注意:我还使用自定义查询集来隐藏未列出的授权对象。

2 个答案:

答案 0 :(得分:3)

由于您已经将它们隐藏在get_queryset中,只需删除权限即可为您提供404。

编辑:您还可以覆盖View类中的permission_denied方法以抛出另一个异常,这是默认实现:

def permission_denied(self, request, message=None):
    """ If request is not permitted, determine what kind of exception to raise.
    """
    if request.authenticators and not request.successful_authenticator:
        raise exceptions.NotAuthenticated()
    raise exceptions.PermissionDenied(detail=message)

答案 1 :(得分:2)

我认为在这种情况下你可以使用custom exception handler

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response.status_code == 403:            
        response.status_code = 404

    return response

在设置中:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 
'my_project.my_app.utils.custom_exception_handler'
}



第二种方法

from rest_framework.exceptions import APIException


class CustomForbidden(APIException):
    status_code = status.HTTP_404_NOT_FOUND


class CustomPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if not_allowed:
            raise CustomForbidden