Spaces:
Running
Running
Upload session.py
Browse files- app/db/session.py +46 -0
app/db/session.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Generator
|
| 2 |
+
|
| 3 |
+
from sqlalchemy import create_engine
|
| 4 |
+
from sqlalchemy.orm import Session, sessionmaker
|
| 5 |
+
|
| 6 |
+
from app.core.config import settings
|
| 7 |
+
from app.models.ecg import Base
|
| 8 |
+
|
| 9 |
+
# Synchronous engine for database connections (works with SQLite reliably here)
|
| 10 |
+
engine = create_engine(
|
| 11 |
+
settings.DATABASE_URL,
|
| 12 |
+
echo=False,
|
| 13 |
+
future=True,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Session factory
|
| 17 |
+
SessionLocal = sessionmaker(
|
| 18 |
+
bind=engine,
|
| 19 |
+
autocommit=False,
|
| 20 |
+
autoflush=False,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_session() -> Generator[Session, None, None]:
|
| 25 |
+
"""
|
| 26 |
+
FastAPI dependency providing a synchronous Session.
|
| 27 |
+
"""
|
| 28 |
+
db = SessionLocal()
|
| 29 |
+
try:
|
| 30 |
+
yield db
|
| 31 |
+
finally:
|
| 32 |
+
db.close()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def init_db() -> None:
|
| 36 |
+
"""
|
| 37 |
+
Create database tables on startup.
|
| 38 |
+
"""
|
| 39 |
+
Base.metadata.create_all(bind=engine)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def close_engine() -> None:
|
| 43 |
+
"""
|
| 44 |
+
Dispose of the engine on shutdown.
|
| 45 |
+
"""
|
| 46 |
+
engine.dispose()
|