42 lines
893 B
Python
42 lines
893 B
Python
|
|
"""数据库连接与会话管理。"""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from typing import Generator
|
||
|
|
|
||
|
|
from sqlalchemy import create_engine
|
||
|
|
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
||
|
|
|
||
|
|
from app.config import get_settings
|
||
|
|
|
||
|
|
|
||
|
|
class Base(DeclarativeBase):
|
||
|
|
pass
|
||
|
|
|
||
|
|
|
||
|
|
_settings = get_settings()
|
||
|
|
|
||
|
|
import os as _os
|
||
|
|
_pool_size = int(_os.environ.get("DB_POOL_SIZE", "20"))
|
||
|
|
_max_overflow = int(_os.environ.get("DB_MAX_OVERFLOW", "30"))
|
||
|
|
|
||
|
|
_engine_kwargs: dict = dict(
|
||
|
|
echo=_settings.db_echo,
|
||
|
|
future=True,
|
||
|
|
pool_pre_ping=True,
|
||
|
|
pool_size=_pool_size,
|
||
|
|
max_overflow=_max_overflow,
|
||
|
|
)
|
||
|
|
|
||
|
|
engine = create_engine(_settings.db_url, **_engine_kwargs)
|
||
|
|
|
||
|
|
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
|
||
|
|
|
||
|
|
|
||
|
|
def get_db() -> Generator[Session, None, None]:
|
||
|
|
db = SessionLocal()
|
||
|
|
try:
|
||
|
|
yield db
|
||
|
|
finally:
|
||
|
|
db.close()
|