35 lines
1.1 KiB
Python
35 lines
1.1 KiB
Python
|
import csv
|
||
|
from io import TextIOWrapper
|
||
|
from models import db, Asset # Import your database and model
|
||
|
|
||
|
def process_csv(file):
|
||
|
"""
|
||
|
Processes the uploaded CSV file and returns a list of Asset objects.
|
||
|
Raises an exception if the file is invalid or data is incorrect.
|
||
|
"""
|
||
|
csv_file = TextIOWrapper(file, encoding='utf-8')
|
||
|
reader = csv.DictReader(csv_file)
|
||
|
|
||
|
# Validate CSV headers
|
||
|
required_headers = ['assettag', 'hostname', 'warrantyfrom', 'status', 'staffnum']
|
||
|
if not all(header in reader.fieldnames for header in required_headers):
|
||
|
raise ValueError("CSV file must include headers: assettag, hostname, warrantyfrom, status, staffnum.")
|
||
|
|
||
|
# Process each row
|
||
|
assets = []
|
||
|
for row in reader:
|
||
|
# Validate required fields
|
||
|
if not row['assettag']:
|
||
|
raise ValueError("Missing 'assettag' in one or more rows.")
|
||
|
|
||
|
# Create Asset object
|
||
|
assets.append(Asset(
|
||
|
assettag=row['assettag'],
|
||
|
hostname=row['hostname'],
|
||
|
warrantyfrom=row['warrantyfrom'],
|
||
|
status=row['status'],
|
||
|
staffnum=row['staffnum']
|
||
|
))
|
||
|
|
||
|
return assets
|