2

I'm getting a zip file from a remote url in a Flask view and returning it. When use requests to access the Flask view and save the file, I get an error when I try to open the file. However, it seems to work if I do what the view does but in the terminal. Why am I getting this error?

caution:  zipfile comment truncated
error [logFiles.zip]:  missing 3232528480 bytes in zipfile
(attempting to process anyway)

Unzipping the file built in the Flask view fails.

file_name = request.args.get('logFile')
log_file = requests.get(url, params=request_params, stream=True)
response = make_response(log_file.text)
response.headers['Content-Type'] = "application/octet-stream"
response.headers["Content-Disposition"] = "attachment; filename={0}".format(file_name)
return response

Unzipping the file built in the terminal works fine.

response = requests.get(url, params=request_params, stream=True)
with open('zipfile.zip', 'wb') as handle:
    handle.write(response.content)
return handle

I've also tried changing the content-type to application/zip but I get the same result.

davidism
  • 121,510
  • 29
  • 395
  • 339
HeonAle
  • 155
  • 1
  • 10

1 Answers1

4

In the first case, you've used .text:

response = make_response(log_file.text)

In the second case, you've used .content:

handle.write(response.content)

.content is "Content of the response, in bytes." .text is "Content of the response, in unicode."

Since you want a byte stream, use .content.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308