providing a 'save-as' option to user for downloading a file using Python

Viewed 120

I have provided an API to the user to download a file by passing the filename as a URL parameter:

https://example.com/download_file/<filename>

in my python code, I'll use the filename to create the header URL and make a request to another server:

import requests
url = 'http://<route>/{}'.format(filename)
headers = {'Content-Disposition':'attachment; filename="myfile.txt"','User-Agent' : 'baby_yoda','Content-Type' : 'application/octet-stream'}
r = requests.get(url, headers=headers)
return r

This does not provide the 'save as' option to the user on the browser. I know I'm missing something, but not sure what I should be looking for. printing 'r' shows a '200 status' only.

2 Answers

try:

return r.text

requests.get returns an object that contains a lot of information in different attributes. Therefore, to access the body of the resulting file you need to add: .text.

Found the solution:

from flask import Response
import requests
url = 'http://<route>/{}'.format(filename)
headers = {'Content-Disposition':'attachment; filename="myfile.txt"','User-Agent' : 'baby_yoda','Content-Type' : 'application/octet-stream'}
r = requests.get(url, stream=True)
return Response(stream_with_context(r.iter_content(chunk_size=2048)), headers = headers)
Related