diff --git a/database.py b/database.py new file mode 100644 index 0000000..1a78c13 --- /dev/null +++ b/database.py @@ -0,0 +1,21 @@ +import os +import MySQLdb +from fastapi import HTTPException +from dotenv import load_dotenv + +load_dotenv() + +def get_db_connection(): + try: + conn = MySQLdb.connect( + user=os.getenv("DB_USER"), + passwd=os.getenv("DB_PASS"), + host=os.getenv("DB_HOST"), + db=os.getenv("DB_NAME"), + charset='utf8mb4', + cursorclass=MySQLdb.cursors.DictCursor + ) + return conn + except MySQLdb.Error as e: + print(f"Erreur de connexion à la base de données : {e}") + raise HTTPException(status_code=500, detail="Erreur interne du serveur lors de la connexion à la base de données.") \ No newline at end of file diff --git a/main.py b/main.py index 8ac6cc8..e800499 100644 --- a/main.py +++ b/main.py @@ -1,12 +1,8 @@ import os from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware -import MySQLdb -from dotenv import load_dotenv from routers import skills -load_dotenv() - app = FastAPI() origins = [ @@ -21,29 +17,10 @@ app.add_middleware( allow_headers=["*"], ) - -def get_db_connection(): - try: - conn = MySQLdb.connect( - user=os.getenv("DB_USER"), - passwd=os.getenv("DB_PASS"), - host=os.getenv("DB_HOST"), - db=os.getenv("DB_NAME"), - charset='utf8mb4', - cursorclass=MySQLdb.cursors.DictCursor - ) - return conn - except MySQLdb.Error as e: - print(f"Erreur de connexion à la base de données : {e}") - raise HTTPException(status_code=500, detail="Erreur interne du serveur lors de la connexion à la base de données.") - - @app.get("/") def read_root(): return {"status": "API Portfolio fonctionnelle !"} - - app.include_router( skills.router, prefix="/api/skills", diff --git a/routers/skills.py b/routers/skills.py index bee70a3..bb739f1 100644 --- a/routers/skills.py +++ b/routers/skills.py @@ -1,6 +1,6 @@ from fastapi import APIRouter, HTTPException import MySQLdb -from ..main import get_db_connection +from ..database import get_db_connection router = APIRouter()