25 lines
626 B
Python
25 lines
626 B
Python
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from app.core.config import settings
|
|
import pymysql
|
|
|
|
# 注册 MySQL Python SQL Driver
|
|
pymysql.install_as_MySQLdb()
|
|
|
|
engine = create_engine(
|
|
settings.SQLALCHEMY_DATABASE_URL,
|
|
pool_pre_ping=True, # 自动处理断开的连接
|
|
pool_recycle=3600, # 连接回收时间
|
|
)
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
Base = declarative_base()
|
|
|
|
# 依赖项
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close() |