@app.route('/download')
@login_required
def download():
    """Export a CSV of all sales data"""
purchases = Purchase.query.all()
csvfile = cStringIO.StringIO()
headers = ['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', 'coupon_used']
rows = []
for purchase in Purchase.query.all():
    rows.append({'uuid': purchase.uuid, 'recipient_name': purchase.
        recipient_name, 'recipient_email': purchase.recipient_email,
        'shipping_street_address_1': purchase.shipping_street_address_1,
        'shipping_street_address_2': purchase.shipping_street_address_2,
        'shipping_city': purchase.shipping_city, 'shipping_state': purchase
        .shipping_state, 'shipping_zip': purchase.shipping_zip,
        'purchaser_name': purchase.purchaser_name, 'purchaser_email':
        purchase.purchaser_email, 'personal_message': purchase.
        personal_message, 'sold_at': purchase.sold_at.strftime('%c'),
        'coupon_used': purchase.coupon_used})
writer = csv.DictWriter(csvfile, headers)
writer.writeheader()
for row in rows:
    writer.writerow(dict((k, v.encode('utf-8') if type(v) is str else v
        ) for k, v in row.items()))
csvfile.seek(0)
return send_file(csvfile, attachment_filename='sales_export.csv',
    as_attachment=True)
How to stream CSV from Flask via sqlalchemy query?