pythonpython-3.xflaskdownload

Flask - send a bytes downloadable file


So I know you can use flask's send_file method that you choose a path on your computer but in my case, I need to read the file as bytes(because I am sending the file from a different python-client) So I have to send it as bytes and then the server would receive it. but I need to make it so some URL will download you this file can I just return the bytes and it will automatically download the file? so something like this:

f = b""
with open("/somefile.txt", "rb") as some_file:
    f = some_file.read()

return f # and make this download the file that I read

Solution

  • Below is an example adjusted from: https://flask.palletsprojects.com/en/stable/patterns/streaming/

    You need a generator function which yields the data,
    and then to call that function from the Response object.

    from flask import Response 
    
    @app.route("/")
    def index():
        def generate():
            with open('somefile.txt','rb') as f:
                for row in f:
                    yield row 
        return Response(generate(), mimetype='text/csv')
    

    Then when you visit this route in the browser, you're immediately prompted to download the streaming data.