Django REST Framework-如何返回404错误而不是403错误 [英] Django REST Framework - How to return 404 error instead of 403
问题描述
仅当用户通过身份验证且满足某些其他条件时,我的API才允许访问(任何请求).
My API allows access (any request) to certain objects only when a user is authenticated and certain other conditions are satisfied.
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错误?
If a user attempts to view a non-authorized object DRF returns a 403 error, however, this gives away that an object with the requested id exists. How can I return 404 errors in these cases?
注意:我还使用自定义查询集来隐藏未经授权的对象,以免被列出.
Note: I also use a custom queryset to hide non-authorized objects from being listed.
推荐答案
由于您已经将它们隐藏在get_queryset中,因此只需删除权限即可获得404的补偿.
As you already hide them in get_queryset just removing the permission will net you a 404 instead.
您还可以在View类中重写Permission_denied方法以引发另一个异常,这是默认实现:
edit: you can also override the permission_denied method in your View class to throw another exception, this is the default implementation:
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)
这篇关于Django REST Framework-如何返回404错误而不是403错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!