通过Django REST API POST调用上传媒体文件(.mp4)时出现MultiValueDictKeyError

时间:2019-02-28 06:03:13

标签: python django file-upload django-rest-framework

我是Django REST Framework的新手。我创建了一个API,该API以MP4文件作为输入,对其进行处理并给出响应。我可以通过API浏览器页面上传文件并获取结果。但是,当我尝试通过本地python文件调用API时,出现以下错误:

  

/ api /'文件'中的MultiValueDictKeyError

     

请求方法:POST

API调用:

import requests
import json
url = 'http://182.xx.xx.xx:8000/api/'
video_file = '/home/lueinuser/Downloads/original.mp4' # 30 MB file in my Local system
payload = {'file' : video_file}
r = requests.post(url=url,data=payload)
print(r.text)

Views.py

class ApiCallingListView(generics.ListCreateAPIView):
    queryset = ApiCallingModel.objects.all()
    serializer_class = ApiCallingSerializer
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request, format=None, *args, **kwargs):
        file_serializer = ApiCallingSerializer(data=request.data)
        file = request.FILES['file']
        fs = FileSystemStorage()
        filename = fs.save(file.name, file)
        uploaded_file_url = settings.MEDIA_ROOT  + '/' + str(filename)
        data_dict = {'video_file': request.FILES}
        request.data['response']= api_wrapper(uploaded_file_url)

        if file_serializer.is_valid():
            file_serializer.save()
            return Response(file_serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Models.py

class ApiCallingModel(models.Model):
    file = models.FileField(blank=False, null=False)
    user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    response = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)

1 个答案:

答案 0 :(得分:0)

您没有正确发送文件:

video_file = '/home/lueinuser/Downloads/original.mp4' # this is just a string, not the content of the file

您需要open这样的文件:

video_file = open('/home/lueinuser/Downloads/original.mp4','rb')

然后使用名为request.post而不是files的实参调用data

video_file = open('/home/lueinuser/Downloads/original.mp4','rb')
files = {'file': video_file}
r = requests.post(url, files=files)

请参见docs