Flask button to save table from query as csv Flask button to save table from query as csv flask flask

Flask button to save table from query as csv


I solved this myself. For anyone who comes across this I find it valuable for the specific use case within flask. Here's what I did.

import cx_Oracle      # We are an Oracle shop, and this changes some thingsimport csvimport StringIO       # allows you to store response object in memory instead of on diskfrom flask import Flask, make_response # Necessary imports, should be obvious@app.route('/export/<int:identifier>', methods=['GET'])def export(load_file_id):    si = StringIO.StringIO()    cw = csv.writer(si)    c = g.db.cursor()    c.execute('SELECT * FROM TABLE WHERE column_val = :identifier', identifier=identifier)    rows = c.fetchall()    cw.writerow([i[0] for i in c.description])    cw.writerows(rows)    response = make_response(si.getvalue())    response.headers['Content-Disposition'] = 'attachment; filename=report.csv'    response.headers["Content-type"] = "text/csv"    return response