Improved export_csv script without file creation

This commit is contained in:
Candifloss 2025-02-11 15:45:41 +05:30
parent 6eebd6a095
commit 2e6589ae1b

View File

@ -1,13 +1,14 @@
from flask import Blueprint, send_file from flask import Blueprint, Response
from models import Asset from models import Asset
import csv import csv
import io
export_csv_bp = Blueprint('export_csv', __name__) export_csv_bp = Blueprint('export_csv', __name__)
@export_csv_bp.route('/export_csv', methods=['POST']) @export_csv_bp.route('/export_csv', methods=['POST'])
def export_csv(): def export_csv():
outfile = open('inventory_export.csv', 'w', newline='') output = io.StringIO()
outcsv = csv.writer(outfile, delimiter='|') outcsv = csv.writer(output, delimiter='|')
records = Asset.query.all() # Fetch all records from the database records = Asset.query.all() # Fetch all records from the database
@ -18,7 +19,11 @@ def export_csv():
for record in records: for record in records:
outcsv.writerow([getattr(record, column.name) for column in Asset.__mapper__.columns]) 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 # Send the file as a download
return send_file('inventory_export.csv', as_attachment=True) return Response(
output.getvalue(),
mimetype="text/csv",
headers={"Content-Disposition": "attachment; filename=inventory_export.csv"}
)