|
| 1 | +from fastapi import APIRouter, UploadFile, File, HTTPException |
| 2 | + |
| 3 | +import csv |
| 4 | +import psycopg2 |
| 5 | +import os |
| 6 | +import io |
| 7 | +from dotenv import load_dotenv |
| 8 | + |
| 9 | +router = APIRouter() |
| 10 | + |
| 11 | +@router.post("/import-csv") |
| 12 | +def import_csv(file: UploadFile = File(...)): |
| 13 | + """Import products from a CSV file into the database.""" |
| 14 | + load_dotenv() |
| 15 | + conn = psycopg2.connect( |
| 16 | + host=os.getenv('DB_HOST'), |
| 17 | + port=os.getenv('DB_PORT', '5432'), |
| 18 | + dbname=os.getenv('DB_NAME'), |
| 19 | + user=os.getenv('DB_USER'), |
| 20 | + password=os.getenv('DB_PASSWORD') |
| 21 | + ) |
| 22 | + cur = conn.cursor() |
| 23 | + try: |
| 24 | + reader = csv.DictReader(io.TextIOWrapper(file.file, encoding='utf-8')) |
| 25 | + batch = [] |
| 26 | + batch_size = 100 |
| 27 | + inserted = 0 |
| 28 | + for row in reader: |
| 29 | + batch.append(( |
| 30 | + row.get('name'), |
| 31 | + row.get('description'), |
| 32 | + float(row.get('price', 0)), |
| 33 | + int(row.get('in_stock', 0)), |
| 34 | + )) |
| 35 | + if len(batch) >= batch_size: |
| 36 | + cur.executemany( |
| 37 | + "INSERT INTO product (name, description, price, in_stock) VALUES (%s, %s, %s, %s)", |
| 38 | + batch |
| 39 | + ) |
| 40 | + conn.commit() |
| 41 | + inserted += len(batch) |
| 42 | + batch.clear() |
| 43 | + if batch: |
| 44 | + cur.executemany( |
| 45 | + "INSERT INTO product (name, description, price, in_stock) VALUES (%s, %s, %s, %s)", |
| 46 | + batch |
| 47 | + ) |
| 48 | + conn.commit() |
| 49 | + inserted += len(batch) |
| 50 | + return {"inserted": inserted} |
| 51 | + except Exception as e: |
| 52 | + conn.rollback() |
| 53 | + raise HTTPException(status_code=500, detail=str(e)) |
| 54 | + finally: |
| 55 | + cur.close() |
| 56 | + conn.close() |
0 commit comments