nastyn8 nastyn8 - 4 months ago 38
Python Question

Invalid file error when trying to open file - Requests and Django

I'm using requests module with Django and trying to send a file from a form but when I do I get "invalid file :" error when I try to open the file. I think that it's only trying to open the filename as a string instead of opening the actual file. How can I go about opening the actual file from the form instead of just trying to open the filename, so I can send it as a payload?

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

Answer

open(file, 'rb') receiving django model object from file = form.save(commit=False) line, not file. send original file. You can do something like

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

Edit:

No need to call open on the file, it's already open. open(file, 'rb') takes file path. the file is already open from above lines just use that. best practice

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