如何在视图集中返回403而不是404

2024-04-29 07:12:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个API,并具有以下视图集:

class ProjectViewSet(viewsets.ModelViewSet):
    # API endpoint that allows projects to be viewed or edited.
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
    authentication_classes = used_authentication_classes
    permission_classes = (IsOwner,)

    @detail_route(methods=['get'])
    def functions(self, request, pk=None):
        project = self.get_object()
        if project is None:
            return Response({'detail': 'Missing project id'}, status=404)
        return Response([FunctionSerializer(x).data for x in Function.objects.filter(project=project)])

权限系统附加到此API。权限对单个资源有效。但是当我调用api/projects它应该返回用户有权访问的所有项目时,它实际上返回了所有的项目,而不管用户是否能够在列表中获得某个项目。在

因此,我重写了get_queryset方法,只返回用户有权访问的项目:

^{pr2}$

这是可行的,但是现在当我请求一个我无权访问的特定资源时,API返回404而不是403。在

我理解为什么,因为我试图从资源中获取的PK是未定义的,因为我只返回用户有权访问的项目。我不明白怎么解决这个问题。在

有人知道我怎样才能让它返回403,或者我应该去哪里看看?在


Tags: 项目用户selfprojectapigetauthenticationobjects
1条回答
网友
1楼 · 发布于 2024-04-29 07:12:13

正如@Alasdair所说404是一个深思熟虑的选择,但是如果你仍然想得到403,你可以试试:

def get_queryset(self):
    user = self.request.user
    allow_all = user.is_superuser or user.is_staff
    if self.action == 'list' and not allow_all:
        return Project.objects.filter(user=user)
    return Project.objects.all()

相关问题 更多 >