-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
38 lines (31 loc) · 1.09 KB
/
database.py
File metadata and controls
38 lines (31 loc) · 1.09 KB
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
import os
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 1. Fetch the URL from the environment
DATABASE_URL = os.getenv("DATABASE_URL")
# 2. Fix the Render 'postgres://' vs SQLAlchemy 'postgresql://' issue
if DATABASE_URL and DATABASE_URL.startswith("postgres://"):
DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)
# 3. Fallback for local development if DATABASE_URL is missing
if not DATABASE_URL:
DATABASE_URL = "sqlite:///./local.db"
print("⚠️ DATABASE_URL not found, falling back to local SQLite.")
# 4. Create the SQLAlchemy engine
# Added 'pool_recycle' to prevent connection timeouts on Render
engine = create_engine(
DATABASE_URL,
pool_pre_ping=True,
pool_recycle=300
)
# 5. Create a session factory
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Base class for our database models
Base = declarative_base()
# Dependency for FastAPI
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()