Spaces:
Running
Running
File size: 1,433 Bytes
8ddf321 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | # File: backend/database.py
import os
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from dotenv import load_dotenv, find_dotenv
# Load environment variables from a .env file if it exists
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
load_dotenv(os.path.join(BASE_DIR, '.env')) # Looks in backend/.env
load_dotenv(os.path.join(ROOT_DIR, '.env')) # Looks in DocuSort/.env
# 1. Check for a cloud-provided database URL first.
# 2. Fall back to your local PostgreSQL setup if DATABASE_URL isn't set.
SQLALCHEMY_DATABASE_URL = os.environ.get(
"DATABASE_URL",
"postgresql://postgres:admin123@localhost/docusort_db"
)
# Fix for cloud hosting environments (like Render/Neon) that might pass "postgres://"
if SQLALCHEMY_DATABASE_URL.startswith("postgres://"):
SQLALCHEMY_DATABASE_URL = SQLALCHEMY_DATABASE_URL.replace("postgres://", "postgresql://", 1)
# Create the engine that communicates with the database
engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
# Create a session factory
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Base class for our database models
Base = declarative_base()
# Dependency to get the DB session in other files
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close() |