Improved export_csv script without file creation
This commit is contained in:
parent
6eebd6a095
commit
2e6589ae1b
@ -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)
|
||||
return Response(
|
||||
output.getvalue(),
|
||||
mimetype="text/csv",
|
||||
headers={"Content-Disposition": "attachment; filename=inventory_export.csv"}
|
||||
)
|
Loading…
Reference in New Issue
Block a user