0

I have a huge csv file being called by another asp script, because the file is so big the asp script times out waiting for a response before the file is finished generating and as a result the csv doesn't download. Is there a way in flask to either return a blank response while the csv is being generated or return the csv file one line at a time?

Simon Melouah
  • 642
  • 4
  • 11
  • 24

1 Answers1

6

You can stream your data using Flask like this:

This is a basic view function that generates a lot of CSV data on the fly. The trick is to have an inner function that uses a generator to generate data and to then invoke that function and pass it to a response object:

from flask import Response

@app.route('/large.csv')
def generate_large_csv():
    def generate():
        for row in iter_all_rows():
            yield ','.join(row) + '\n'
    return Response(generate(), mimetype='text/csv')

Each yield expression is directly sent to the browser. Note though that some WSGI middlewares might break streaming, so be careful there in debug environments with profilers and other things you might have enabled.

For more information click here

Amin Alaee
  • 1,895
  • 17
  • 26