Jelajahi Sumber

chore: auto-load .env if python-dotenv present; document python-dotenv in README

tanlie 1 bulan lalu
induk
melakukan
582af97e46
2 mengubah file dengan 18 tambahan dan 0 penghapusan
  1. 2 0
      FastApi/README.md
  2. 16 0
      FastApi/app/core/db.py

+ 2 - 0
FastApi/README.md

@@ -23,6 +23,8 @@ Dependencies
 Install runtime dependencies for database access:
 
 pip install sqlalchemy pymysql
+# Optional: install python-dotenv to auto-load a .env file located at project root
+pip install python-dotenv
 
 Running
 -------

+ 16 - 0
FastApi/app/core/db.py

@@ -12,6 +12,22 @@ Install dependencies: pip install sqlalchemy pymysql
 import os
 from typing import Generator
 
+# Try to auto-load a local .env file if python-dotenv is available.
+# Python does not read .env files automatically, so without this the app
+# will only see environment variables explicitly set in the process.
+try:
+    from dotenv import load_dotenv
+    # Prefer project-level .env (FastApi/.env) then repository root .env
+    base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
+    env_paths = [os.path.join(base_dir, ".env"), os.path.join(os.path.dirname(base_dir), ".env")]
+    for p in env_paths:
+        if os.path.exists(p):
+            load_dotenv(p, override=False)
+            break
+except Exception:
+    # dotenv not installed; skip silently
+    pass
+
 from sqlalchemy import create_engine
 from sqlalchemy.engine import URL
 from sqlalchemy.orm import sessionmaker, declarative_base