Improved export_csv.py
This commit is contained in:
parent
2e6589ae1b
commit
a7265dc6c1
@ -7,23 +7,28 @@ export_csv_bp = Blueprint('export_csv', __name__)
|
||||
|
||||
@export_csv_bp.route('/export_csv', methods=['POST'])
|
||||
def export_csv():
|
||||
# Create an in-memory file-like object
|
||||
output = io.StringIO()
|
||||
outcsv = csv.writer(output, delimiter='|')
|
||||
writer = csv.writer(output, delimiter='|')
|
||||
|
||||
records = Asset.query.all() # Fetch all records from the database
|
||||
# Fetch all records from the database
|
||||
records = Asset.query.all()
|
||||
|
||||
# Write headers
|
||||
outcsv.writerow([column.name for column in Asset.__mapper__.columns])
|
||||
writer.writerow([column.name for column in Asset.__mapper__.columns])
|
||||
|
||||
# Write data rows
|
||||
for record in records:
|
||||
outcsv.writerow([getattr(record, column.name) for column in Asset.__mapper__.columns])
|
||||
writer.writerow([getattr(record, column.name) for column in Asset.__mapper__.columns])
|
||||
|
||||
output.seek(0) # Move cursor to the beginning
|
||||
|
||||
# Send the file as a download
|
||||
return Response(
|
||||
# Prepare the response
|
||||
response = Response(
|
||||
output.getvalue(),
|
||||
mimetype="text/csv",
|
||||
headers={"Content-Disposition": "attachment;filename=inventory_export.csv"}
|
||||
)
|
||||
|
||||
# Close the in-memory file-like object
|
||||
output.close()
|
||||
|
||||
return response
|
Loading…
Reference in New Issue
Block a user