flask make_response with large files flask make_response with large files flask flask

flask make_response with large files


See the docs on Streaming Content. Basically, you write a function that yields chunks of data, and pass that generator to the response, rather than the whole thing at once. Flask and your web server do the rest.

from flask import stream_with_context, Response@app.route('/stream_data')def stream_data():    def generate():        # create and return your data in small parts here        for i in xrange(10000):            yield str(i)    return Response(stream_with_context(generate()))

If the file is static, you can instead take advantage of send_from_directory(). The docs advise you to use nginx or another server that supports X-SendFile, so that reading and sending the data is efficient.


The problem in your attempt is, that you are first reading complete content into "raw_bytes", so with large files you are easy to exhaust all the memory you have.

There are multiple options to resolve that:

Streaming the content

As explained by davidism answer, you can use a generator passed int Response. This serves the large file piece by piece and does not require so much memory.

The streaming can go not only from a generator, but also from a file, as shown in this anwer

Serving static files over flask

In case your file is static, search for how to configure Flask to serve static files. These shall be automatically served in streaming manner.

Serving static files over apache or nginx (or other web server)

Assuming, the file is static, you shall in production serve it by reverse proxy in front of your Flask app. This not only offloads your app, but also works much faster.