2025-02-11 10:15:41 +00:00
|
|
|
from flask import Blueprint, Response
|
2025-02-11 18:45:53 +00:00
|
|
|
from definitions.models import Asset
|
2025-02-11 07:47:57 +00:00
|
|
|
import csv
|
2025-02-11 10:15:41 +00:00
|
|
|
import io
|
2025-02-11 07:47:57 +00:00
|
|
|
|
|
|
|
export_csv_bp = Blueprint('export_csv', __name__)
|
|
|
|
|
|
|
|
@export_csv_bp.route('/export_csv', methods=['POST'])
|
|
|
|
def export_csv():
|
2025-02-11 12:22:06 +00:00
|
|
|
# Create an in-memory file-like object
|
2025-02-11 10:15:41 +00:00
|
|
|
output = io.StringIO()
|
2025-02-11 12:22:06 +00:00
|
|
|
writer = csv.writer(output, delimiter='|')
|
|
|
|
|
|
|
|
# Fetch all records from the database
|
|
|
|
records = Asset.query.all()
|
|
|
|
|
2025-02-11 07:47:57 +00:00
|
|
|
# Write headers
|
2025-02-11 12:22:06 +00:00
|
|
|
writer.writerow([column.name for column in Asset.__mapper__.columns])
|
|
|
|
|
2025-02-11 07:47:57 +00:00
|
|
|
# Write data rows
|
|
|
|
for record in records:
|
2025-02-11 12:22:06 +00:00
|
|
|
writer.writerow([getattr(record, column.name) for column in Asset.__mapper__.columns])
|
|
|
|
|
|
|
|
# Prepare the response
|
|
|
|
response = Response(
|
2025-02-11 10:15:41 +00:00
|
|
|
output.getvalue(),
|
|
|
|
mimetype="text/csv",
|
2025-02-11 12:22:06 +00:00
|
|
|
headers={"Content-Disposition": "attachment;filename=inventory_export.csv"}
|
|
|
|
)
|
|
|
|
|
|
|
|
# Close the in-memory file-like object
|
|
|
|
output.close()
|
|
|
|
|
|
|
|
return response
|