flask_crud_app/functions/process_csv.py

28 lines
1.1 KiB
Python
Raw Permalink Normal View History

2025-01-30 07:37:21 +00:00
import csv
from io import TextIOWrapper
2025-02-11 08:14:14 +00:00
from config import item_attributes
2025-01-30 07:37:21 +00:00
2025-01-30 09:58:34 +00:00
def get_csv_data(file):
2025-01-30 07:37:21 +00:00
csv_file = TextIOWrapper(file, encoding='utf-8')
2025-01-30 09:58:34 +00:00
reader = csv.DictReader(csv_file, delimiter='|')
2025-01-30 07:37:21 +00:00
2025-02-11 08:14:14 +00:00
# Validate CSV headers based on config
required_headers = {attrib.display_name for attrib in item_attributes} # Use display names
csv_headers = set(reader.fieldnames) # Get headers present in the CSV file
# Check if the required headers exist
if not required_headers.issubset(csv_headers):
2025-02-11 08:14:14 +00:00
raise ValueError(f"CSV file must include headers: {', '.join(required_headers)}.")
# Check for invalid headers
2025-02-11 18:45:53 +00:00
if extra_headers := csv_headers - required_headers:
raise ValueError(f"Unexpected headers found: {', '.join(extra_headers)}")
2025-01-30 07:37:21 +00:00
# Map display names to attribute names
display_to_attrib = {attrib.display_name: attrib.attrib_name for attrib in item_attributes}
2025-02-11 08:14:14 +00:00
# Extract data dynamically based on config
return [
{display_to_attrib[header]: row[header] for header in required_headers}
for row in reader
]