From 8304940dafa8894ff200b97eeab25e706eb0baa3 Mon Sep 17 00:00:00 2001 From: Giovanni-Josserand Date: Fri, 29 Aug 2025 18:40:08 +0200 Subject: [PATCH] update requierements.txt, add of db connection function and root --- .env | 4 ++++ main.py | 61 ++++++++++++++++++++++++++++++++---------------- requirements.txt | 3 ++- test.txt | 0 4 files changed, 47 insertions(+), 21 deletions(-) create mode 100644 .env delete mode 100644 test.txt diff --git a/.env b/.env new file mode 100644 index 0000000..75d0e3d --- /dev/null +++ b/.env @@ -0,0 +1,4 @@ +DB_USER="portfolio_user" +DB_PASS="USER@gio53" +DB_HOST="localhost" +DB_NAME="portfolio" \ No newline at end of file diff --git a/main.py b/main.py index 72da5be..4e54c7a 100644 --- a/main.py +++ b/main.py @@ -1,21 +1,42 @@ -from fastapi import FastAPI -import mariadb -app = FastAPI() +import os +from fastapi import FastAPI, HTTPException +from fastapi.middleware.cors import CORSMiddleware +import MySQLdb +from dotenv import load_dotenv -@app.get("/api/portfolio") -def read_portfolio(): - try: - conn = mariadb.connect( - user="root", - password="motdepasse", - host="localhost", - port=3306, - database="portfolio" - ) - cursor = conn.cursor() - cursor.execute("SELECT * FROM portfolio;") - result = cursor.fetchall() - conn.close() - return {"data": result} - except mariadb.Error as e: - return {"error": str(e)} \ No newline at end of file +load_dotenv() + +app = FastAPI() + +origins = [ + "http://localhost", + "http://localhost:5173", +] +app.add_middleware( + CORSMiddleware, + allow_origins=origins, + allow_credentials=True, + allow_methods=["*"], + 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"} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 63875dc..83cca42 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ fastapi uvicorn -mariadb \ No newline at end of file +mysqlclient +python-dotenv \ No newline at end of file diff --git a/test.txt b/test.txt deleted file mode 100644 index e69de29..0000000