Skip to content

Commit 888a74d

Browse files
committed
/import-csv
1 parent d749521 commit 888a74d

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

app/api/import_csv.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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()

app/api/routes.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,10 @@
1717
from app.api.root import router as root_router
1818
from app.api.health import router as health_router
1919
from app.api.echo import router as echo_router
20+
from app.api.import_csv import router as import_csv_router
2021

2122
router.include_router(root_router)
2223
router.include_router(health_router)
2324
router.include_router(echo_router)
25+
router.include_router(import_csv_router)
2426

0 commit comments

Comments
 (0)