From 2e6589ae1b3fb03fe1631a8e901b6dbfa6b864cb Mon Sep 17 00:00:00 2001 From: candifloss Date: Tue, 11 Feb 2025 15:45:41 +0530 Subject: [PATCH] Improved export_csv script without file creation --- routes/export_csv.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/routes/export_csv.py b/routes/export_csv.py index 647bd18..6410da5 100644 --- a/routes/export_csv.py +++ b/routes/export_csv.py @@ -1,13 +1,14 @@ -from flask import Blueprint, send_file +from flask import Blueprint, Response from models import Asset import csv +import io export_csv_bp = Blueprint('export_csv', __name__) @export_csv_bp.route('/export_csv', methods=['POST']) def export_csv(): - outfile = open('inventory_export.csv', 'w', newline='') - outcsv = csv.writer(outfile, delimiter='|') + output = io.StringIO() + outcsv = csv.writer(output, delimiter='|') records = Asset.query.all() # Fetch all records from the database @@ -18,7 +19,11 @@ def export_csv(): for record in records: outcsv.writerow([getattr(record, column.name) for column in Asset.__mapper__.columns]) - outfile.close() + output.seek(0) # Move cursor to the beginning # Send the file as a download - return send_file('inventory_export.csv', as_attachment=True) \ No newline at end of file + return Response( + output.getvalue(), + mimetype="text/csv", + headers={"Content-Disposition": "attachment; filename=inventory_export.csv"} + ) \ No newline at end of file