flask_crud_app/routes/upload.py

48 lines
1.6 KiB
Python
Raw Normal View History

2025-02-01 17:53:13 +00:00
from flask import Blueprint, request, render_template, redirect, session
2025-01-30 09:58:34 +00:00
import csv
from io import TextIOWrapper
2025-02-01 17:53:13 +00:00
from models import Asset, db
2025-01-30 09:58:34 +00:00
from process_csv import get_csv_data # Import the CSV processing function
2025-01-30 07:37:21 +00:00
2025-01-30 09:58:34 +00:00
# Create a Blueprint for upload
2025-01-30 07:37:21 +00:00
upload_bp = Blueprint('uploadcsv', __name__)
@upload_bp.route('/uploadcsv', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# Check if a file was uploaded
if 'file' not in request.files:
2025-01-30 09:58:34 +00:00
return redirect('uploadcsv')
2025-01-30 07:37:21 +00:00
file = request.files['file']
# Check if the file is a CSV
if file.filename == '' or not file.filename.endswith('.csv'):
2025-01-30 09:58:34 +00:00
return redirect('uploadcsv')
2025-01-30 07:37:21 +00:00
try:
2025-01-30 09:58:34 +00:00
# Extract data from the CSV file
2025-02-05 08:26:37 +00:00
csvdata = get_csv_data(file)
new_assets = []
existing_assets = []
for row in csvdata:
tag = row['assettag']
asset_exists = Asset.query.filter_by(assettag=tag).first()
if asset_exists:
existing_assets.append(row)
else:
new_assets.append(row)
session['assets'] = new_assets # Store assets in session
2025-01-30 07:37:21 +00:00
2025-01-30 09:58:34 +00:00
# Redirect to preview page with the CSV data
2025-02-05 08:26:37 +00:00
return render_template('csv_preview.html', new_assets=new_assets, existing=existing_assets)
2025-01-30 07:37:21 +00:00
except Exception as e:
# Handle errors during file processing
2025-01-30 09:58:34 +00:00
print(f"Error processing CSV file: {str(e)}")
return redirect('uploadcsv')
2025-01-30 07:37:21 +00:00
# Render the upload page for GET requests
2025-02-01 17:53:13 +00:00
return render_template('upload.html')