-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
29 lines (23 loc) · 906 Bytes
/
database.py
File metadata and controls
29 lines (23 loc) · 906 Bytes
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
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
# Fallback to sqlite if postgres is not available for easy local testing
POSTGRES_URL = "postgresql://user:password@localhost/dbname"
SQLITE_URL = "sqlite:///./sql_app.db"
# Select database URL based on environment variable (defaulting to SQLite for portability)
SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL", SQLITE_URL)
if SQLALCHEMY_DATABASE_URL.startswith("sqlite"):
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
else:
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""Dependency for injecting database sessions."""
db = SessionLocal()
try:
yield db
finally:
db.close()