I'd like to stream a CSV from Flask using the technique they describe here:
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')
I have a query from sqlalchemy that returns a list of Purchase objects. I'd like to write this to a CSV, ideally with customization over the attributes output to the file.
Unfortunately, I'm getting a blank CSV as output currently:
@app.route('/sales_export.csv')
@login_required
def sales_export():
""" Export a CSV of all sales data """
def generate():
count = 0
fieldnames = [
'uuid',
'recipient_name',
'recipient_email',
'shipping_street_address_1',
'shipping_street_address_2',
'shipping_city',
'shipping_state',
'shipping_zip',
'purchaser_name',
'purchaser_email',
'personal_message',
'sold_at'
]
for i, row in enumerate(Purchase.query.all()):
if i == 0:
yield fieldnames
csv = ','.join(row) + '\n'
yield csv
return Response(generate(), mimetype='text/csv')
Where am I going wrong?