import StringIO
import csv
from flask import make_response
@app.route('/download/<obj>/')
def download(obj):
f = StringIO()
writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_ALL, lineterminator="\n")
if obj == 'users':
writer.writerow(['id','username','gender','age','created_at'])
for u in User.query.all():
writer.writerow([u.id, u.username,u.gender,u.age,u.created_at])
res = make_response()
res.data = f.getvalue()
res.headers['Content-Type'] = 'text/csv'
res.headers['Content-Disposition'] = 'attachment; filename='+ obj +'.csv'
return res
Click here for details
Click here for more about headers[‘Content-Disposition’]