I have an APIView as below and need to 'post' based on the content type header.
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'.
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.
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. I can post to upload the file but the JSON post serializer expects the 'file' and throws a 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.
Resolved with the following solution using if up_file is not None
:
Thank you @RahulGupta for your assistance!
# 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.