flask_crud_app/routes/export_csv.py

36 lines
1.0 KiB
Python

from flask import Blueprint, Response
from definitions.models import Asset
from config import item_attributes
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 (use display names from item_attributes)
headers = [attrib.display_name for attrib in item_attributes]
writer.writerow(headers)
# Write data rows
for record in records:
writer.writerow([getattr(record, attrib.attrib_name) for attrib in item_attributes])
# 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