From 5a5997aa55055b9c583700b374fabcd3e1876691 Mon Sep 17 00:00:00 2001 From: Gilles Soulier Date: Sun, 24 May 2026 05:08:50 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20seed=20donn=C3=A9es=20initiales=20(114?= =?UTF-8?q?=20produits=20+=209=20magasins)=20au=20d=C3=A9marrage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/data/seed.py | 42 ++++++++++++++++++++++++++++++++++++++++ backend/app/main.py | 11 ++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 backend/app/data/seed.py diff --git a/backend/app/data/seed.py b/backend/app/data/seed.py new file mode 100644 index 0000000..6a12991 --- /dev/null +++ b/backend/app/data/seed.py @@ -0,0 +1,42 @@ +""" +Lance le seed uniquement si la table shopping.stores est vide. +Usage : python -m app.data.seed +""" +import asyncio +import json +from pathlib import Path + +from sqlalchemy import select + +from app.core.database import AsyncSessionLocal +from app.models.shopping import Product, Store + +DATA_DIR = Path(__file__).parent + + +async def run_seed() -> None: + async with AsyncSessionLocal() as session: + count = await session.scalar(select(Store).limit(1)) + if count is not None: + print("Seed déjà chargé — rien à faire.") + return + + stores_raw = json.loads((DATA_DIR / "seed_stores.json").read_text()) + for s in stores_raw: + session.add(Store(name=s["name"], location=s.get("location"))) + + products_raw = json.loads((DATA_DIR / "seed_products.json").read_text()) + for p in products_raw: + session.add(Product( + name=p["name"], + category=p.get("category"), + default_unit=p.get("default_unit"), + frequency_score=p.get("frequency_score", 0), + )) + + await session.commit() + print(f"Seed : {len(stores_raw)} magasins, {len(products_raw)} produits chargés.") + + +if __name__ == "__main__": + asyncio.run(run_seed()) diff --git a/backend/app/main.py b/backend/app/main.py index cf7a5ca..a958fe4 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,10 +1,19 @@ +from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.api.health import router as health_router from app.api.media import router as media_router from app.core.config import settings +from app.data.seed import run_seed -app = FastAPI(title="HomeHub API", version="0.1.0") + +@asynccontextmanager +async def lifespan(app: FastAPI): + await run_seed() + yield + + +app = FastAPI(title="HomeHub API", version="0.1.0", lifespan=lifespan) app.add_middleware( CORSMiddleware,