Spaces:
Running on Zero
Running on Zero
File size: 1,175 Bytes
0fe62e1 847e49a 0fe62e1 847e49a 0fe62e1 847e49a | 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 42 43 44 45 46 47 48 49 50 51 52 | # database.py
import os
import tempfile
from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
# ✅ load .env file
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
if not DATABASE_URL:
try:
test_path = "./.write_test"
with open(test_path, "w") as f:
f.write("ok")
os.remove(test_path)
DATABASE_URL = "sqlite:///./toxiguard.db"
except Exception:
db_dir = os.environ.get("HF_HOME", tempfile.gettempdir())
DATABASE_URL = f"sqlite:///{os.path.join(db_dir, 'toxiguard.db')}"
# Fix for Render (postgres)
if DATABASE_URL.startswith("postgres://"):
DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)
# SQLite fix
connect_args = {"check_same_thread": False} if "sqlite" in DATABASE_URL else {}
engine = create_engine(
DATABASE_URL,
connect_args=connect_args,
pool_pre_ping=True
)
SessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=engine
)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
|