简体   繁体   English

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

[英]Python/Django REST Framework POST based on Content-Type header

I have an APIView as below and need to 'post' based on the content type header. 我有一个如下的APIView,需要基于内容类型标头进行“发布”。

We are working with an external PUSH API that needs to post to a single endpoint, firstly JSON data with 'application/json' and then upload a file with 'multipart/form-data'. 我们正在使用一个外部PUSH API,该API需要发布到单个端点,首先使用'application / json'发布JSON数据,然后使用'multipart / form-data'上传一个文件。

The below view works to post one or the other if one is removed ie: just upload file or just post JSON but I can't seem have the view choose to upload the file or post the JSON based on the 'content-type' received with the post. 下面的视图可以发布一个或另一个(如果已删除),即:仅上传文件或仅发布JSON,但我似乎无法根据接收到的“内容类型”选择上传文件或发布JSON与职位。

If there is no file in request.data['file'] I would like to only post the JSON data and if there is a file then just upload the file. 如果request.data['file']没有文件,我只想发布JSON数据,如果有文件,则只需上传文件。 I can post to upload the file but the JSON post serializer expects the 'file' and throws a KeyError. 我可以发布以上传文件,但是JSON发布序列化程序需要'file'并抛出KeyError。

I have tried various iterations of this code, any ideas how to achieve? 我已经尝试了此代码的各种迭代,如何实现?

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)

Try changing 尝试改变

up_file = request.data['file']

to

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

This should prevent the KeyError issue. 这样可以避免KeyError问题。

Resolved with the following solution using if up_file is not None : 使用if up_file is not None的以下解决方案解决:

Thank you @RahulGupta for your assistance! 谢谢@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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM