34 lines
934 B
Python
34 lines
934 B
Python
from flask import Blueprint, Response
|
|
from definitions.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():
|
|
# Create an in-memory file-like object
|
|
output = io.StringIO()
|
|
writer = csv.writer(output, delimiter='|')
|
|
|
|
# Fetch all records from the database
|
|
records = Asset.query.all()
|
|
|
|
# Write headers
|
|
writer.writerow([column.name for column in Asset.__mapper__.columns])
|
|
|
|
# Write data rows
|
|
for record in records:
|
|
writer.writerow([getattr(record, column.name) for column in Asset.__mapper__.columns])
|
|
|
|
# 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 |