41 lines
882 B
Python
41 lines
882 B
Python
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import os
|
|||
|
|
from collections.abc import Generator
|
|||
|
|
from contextlib import contextmanager
|
|||
|
|
|
|||
|
|
from sqlalchemy import create_engine
|
|||
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|||
|
|
|
|||
|
|
|
|||
|
|
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql+psycopg://yg_ft:change_me@localhost:15432/yg_ft")
|
|||
|
|
|
|||
|
|
engine = create_engine(
|
|||
|
|
DATABASE_URL,
|
|||
|
|
pool_pre_ping=True,
|
|||
|
|
future=True,
|
|||
|
|
)
|
|||
|
|
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False, future=True)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def get_db() -> Generator[Session, None, None]:
|
|||
|
|
db = SessionLocal()
|
|||
|
|
try:
|
|||
|
|
yield db
|
|||
|
|
finally:
|
|||
|
|
db.close()
|
|||
|
|
|
|||
|
|
|
|||
|
|
@contextmanager
|
|||
|
|
def session_scope() -> Generator[Session, None, None]:
|
|||
|
|
db = SessionLocal()
|
|||
|
|
try:
|
|||
|
|
yield db
|
|||
|
|
db.commit()
|
|||
|
|
except Exception:
|
|||
|
|
db.rollback()
|
|||
|
|
raise
|
|||
|
|
finally:
|
|||
|
|
db.close()
|
|||
|
|
|