我使用`status = HTTP_404_NOT_FOUND`返回Response,但找到201

时间:2017-11-10 09:47:17

标签: python django

在views.py中,我返回带有status=HTTP_404_NOT_FOUND的响应:

class CloudServerCreateAPIView(CreateAPIView):
    serializer_class = CloudServerCreateSerializer
    permission_classes = []
    queryset = CloudServer.objects.all()

    def perform_create(self, serializer):

        return Response(data="There is no data left.", status=HTTP_404_NOT_FOUND, exception=Exception())

        serializer.save()

但是当我申请API时,我得到HTTP 201 Created,而不是404

POST /api/user_productmanage/cloudserver/create/
HTTP 201 Created
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "expiration_time": "2017-12-11T11:11:11+08:00",
    "profile": "asdas",
    "buytime": 1,
    "availablearea": 2
}

1 个答案:

答案 0 :(得分:2)

你的404逻辑不应该存在于perform_create中。执行创建主要用于注入您在其他地方或用户特定的数据。

例如serializer.save(user=self.request.user, date_time=datetime.now())

尝试将您的逻辑移至createpost方法。我的建议是将其移至post

class CloudServerCreateAPIView(CreateAPIView):
    serializer_class = CloudServerCreateSerializer
    permission_classes = []
    queryset = CloudServer.objects.all()

    def create(self, request, *args, **kwargs):
        # Your reason for 404
        # if reason:
        #     # return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def post(self, request, *args, **kwargs):
        # Your reason for 404
        if reason:
            return Response(data="There is no data left.", status=HTTP_404_NOT_FOUND, exception=Exception())
        return self.create(request, *args, **kwargs)