基于Content-Type标头的Python / Django REST框架POST

时间:2015-09-24 03:12:12

标签: python django api rest django-rest-framework

我有一个如下所示的APIView,需要根据内容类型标题“发布”。

我们正在使用需要发布到单个端点的外部PUSH API,首先是带有'application / json'的JSON数据,然后使用'multipart / form-data'上传文件。

下面的视图适用于发布一个或另一个如果删除一个,即:只是上传文件或只是发布JSON但我似乎无法让视图选择上传文件或发布基于'内容的JSON-输入'收到帖子。

如果request.data['file']中没有文件,我只想发布JSON数据,如果有文件则只上传文件。我可以发布上传文件,但JSON post序列化程序需要'file'并抛出KeyError。

我已尝试过这段代码的各种迭代,任何想法如何实现?

class ridesViewSet(APIView):
    permission_classes = (AllowAny, )
    queryset = rides.objects.all()
    serializer_class = ridesSerializer
    parser_classes = (JSONParser, MultiPartParser, )

    def post(self, request, format=None):

        up_file = None
        if request.content_type == 'multipart/form-data':
            up_file = request.data['file']

        if up_file == None:
            serializer = ridesSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            if socket.getfqdn() == 'STG' or socket.getfqdn() == 'PRD':
                destination = open(PRD_UPLOAD + up_file.name, 'wb+')
            else:
                destination = open('/Users/ncole/Documents/rides/ridesAPI/uploads/' + up_file.name, 'wb+')
            for chunk in up_file.chunks():
                destination.write(chunk)
                destination.close()
            return Response(up_file.name, status=status.HTTP_201_CREATED)

2 个答案:

答案 0 :(得分:0)

尝试更改

up_file = request.data['file']

up_file = request.data.get('file') # use .get() to avoid keyerror

这可以防止KeyError问题。

答案 1 :(得分:0)

使用if up_file is not None解决了以下解决方案:

感谢@RahulGupta的帮助!

# FULL WORKING POST FOR JSON & FILE
def post(self, request, format=None):
    up_file = request.data.get('file')
    serializer = ridesSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        if up_file is not None:
            if socket.getfqdn() == 'STG' or socket.getfqdn() == 'PRD':
                destination = open(PRD_UPLOAD + up_file.name, 'wb+')
            else:
                destination = open('/Users/ncole/Documents/rides/ridesAPI/uploads/' + up_file.name, 'wb+')
            for chunk in up_file.chunks():
                destination.write(chunk)
                destination.close()
            return Response(up_file.name, status=status.HTTP_201_CREATED)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)