尝试打开文件时出现无效的文件错误 - 请求和Django

时间:2016-08-01 15:23:13

标签: python django python-requests

我正在使用带有Django的请求模块并尝试从表单发送文件,但是当我尝试打开文件时,我收到“ invalid file:”错误。我认为它只是尝试将文件名作为字符串打开而不是打开实际文件。如何从表单中打开实际文件而不是仅仅尝试打开文件名,以便将其作为有效负载发送?

class AddDocumentView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    login_url = reverse_lazy('users:login')
    form_class = FileUploadForm
    template_name = 'docman/forms/add-document.html'
    success_message = 'Document was successfully added'

    def form_valid(self, form):
        pk = self.kwargs['pk']
        user = get_object_or_404(User, pk=pk)
        file = form.save(commit=False)
        file.user = user
        if not self.post_to_server(file, user.id):
            file.delete()
        return super(AddDocumentView, self).form_valid(form)

    def post_to_server(self, file, cid):
        url = 'https://example.herokuapp.com/api/files/'
        headers = {'token': '333334wsfSecretToken'}

        # I get error here when trying to open file
        payload = {'file': open(file, 'rb'), 'client_id': cid}
        r = requests.post(url, data=payload, headers=headers)
        print(r.text)
        if r.status_code == requests.codes.ok:
            return True
        else:
            return False

1 个答案:

答案 0 :(得分:2)

open(file, 'rb')file = form.save(commit=False)行接收django模型对象,而不是文件。发送原始文件。 你可以做点什么

file = self.request.FILES.get('name')
self.post_to_server(file, user.id)

编辑:

无需在文件上打开,它已经打开。 open(file, 'rb')采用文件路径。该文件已经从上面的行打开只是使用它。 最佳实践

files = {'file': file}
r = requests.post(url, files=files, data=payload)