Spaces:
Runtime error
Runtime error
File size: 1,906 Bytes
6aa6081 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import csv
import io
from fastapi import HTTPException, status
from typing import List, Tuple, Callable, Any
def generate_csv_template(headers: List[str]) -> str:
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(headers)
return output.getvalue()
def parse_csv_upload(content: str, required_columns: List[str]) -> List[dict]:
reader = csv.DictReader(io.StringIO(content))
if not reader.fieldnames:
raise HTTPException(status_code=400, detail="CSV vacío o sin encabezados")
missing = [c for c in required_columns if c not in reader.fieldnames]
if missing:
raise HTTPException(
status_code=400,
detail=f"Columnas requeridas faltantes: {', '.join(missing)}. Columnas del archivo: {', '.join(reader.fieldnames)}",
)
rows = []
for i, row in enumerate(reader, start=2):
cleaned = {k.strip(): v.strip() if v else "" for k, v in row.items()}
rows.append(cleaned)
return rows
def process_csv_rows(
rows: List[dict],
row_processor: Callable[[dict, int], Tuple[bool, str]],
) -> dict:
created = 0
updated = 0
errors = []
for i, row in enumerate(rows, start=2):
try:
result = row_processor(row, i)
if isinstance(result, str):
if result == "created":
created += 1
elif result == "updated":
updated += 1
else:
errors.append({"row": i, "error": result})
elif isinstance(result, tuple):
ok, msg = result
if ok:
created += 1
else:
errors.append({"row": i, "error": msg})
except Exception as e:
errors.append({"row": i, "error": str(e)})
return {"created": created, "updated": updated, "errors": errors}
|