无法获取POST请求对Django Rest-framework的APIView的响应

时间:2020-01-04 06:59:17

标签: python-3.x django-rest-framework

我正在将发帖请求发送到 OrganisationApiView 类。请求正文包含以下JSON。

{
"organisation_id" : "1",
"organisation_name" "Some Name"
}

views.py

from typing import Optional, Any
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import JSONParser

from . import serializers


class OrganisationApiView(APIView):

    serializers_class = serializers.OrganisationSerializer
    parser_classes = [JSONParser]

    def get(self, request, formate=None):
        return Response({"message": "You are Cool!!"})

    def post(self, request, formate=None):
        serializer = self.serializers_class(data=request.data)
        print(serializer)

        if serializer.is_valid():
            organisation_name = serializer.validated_data.get('organisation_name')
            message = f"Reached POST {organisation_name}"
            return Response({'message': message, status: 'HTTP_200_OK'})
        else:
            return Response(
                serializer.errors,
                status=status.HTTP_400_BAD_REQUEST
            )

    def put(self, request, pk=None):
        return Response({"message": "PUT"})

    def patch(self, request, pk=None):
        return Response({"message": "PATCH"})

    def delete(self, request, pk=None):
        return Response({"message": "Delete"})

我对邮递员的答复是-

TypeError at /api/organisation/
keys must be str, int, float, bool or None, not module
Request Method: POST
Request URL:    http://127.0.0.1:8000/api/organisation/
Django Version: 2.1.15
Exception Type: TypeError
Exception Value:    
keys must be str, int, float, bool or None, not module
Exception Location: /usr/local/lib/python3.7/json/encoder.py in iterencode, line 257
Python Executable:  /usr/local/bin/python
Python Version: 3.7.6
Python Path:    
['/app',
 '/usr/local/lib/python37.zip',
 '/usr/local/lib/python3.7',
 '/usr/local/lib/python3.7/lib-dynload',
 '/usr/local/lib/python3.7/site-packages']
Server time:    Sat, 4 Jan 2020 06:42:54 +0000

其他请求(如GET,PUT,PATCH,DELETE)也可以正常工作。我不明白到底是什么引起了这个问题。我还定义了 SimpleSerializers ,如下所述。

from rest_framework import serializers
class OrganisationSerializer(serializers.Serializer):
    organisation_id = serializers.IntegerField()
    organisation_name = serializers.CharField(max_length=255, allow_null=False, allow_blank=False)

此外,我不想接受 organization_id ,因为在我将其定义为主键的模型中。 但是,当我发送不带 organization_id 的JSON时,它会引发错误,指出字段 organisation_id 是必需的。到目前为止,我只想接受 organization_name (组织名称)并将其返回作为响应。

1 个答案:

答案 0 :(得分:0)

您正在尝试将serializer.errors作为JSON数据返回,但这不是字典,而是模块。您可以改用serializer.error_messages

尝试一下:

else:
    return Response(
        serializer.error_messages,
        status=status.HTTP_400_BAD_REQUEST
    )

更好的解决方案

由于只尝试返回序列化过程的详细信息,因此在调用序列化器的is_valid函数时,可以传递参数以在序列化器无效时触发异常。 serializer.is_valid(raise_exception=True)。其默认格式将满足您的需求。该代码将是:

def post(self, request, formate=None):
    serializer = self.serializers_class(data=request.data)
    serializer.is_valid(raise_exception=True)
    organisation_name = serializer.validated_data.get('organisation_name')
    message = f"Reached POST {organisation_name}"
    return Response({'message': message, status: 'HTTP_200_OK'})