33 lines
659 B
Python
33 lines
659 B
Python
|
|
import os
|
||
|
|
from sqlalchemy import create_engine
|
||
|
|
from sqlalchemy.ext.declarative import declarative_base
|
||
|
|
from sqlalchemy.orm import sessionmaker
|
||
|
|
|
||
|
|
# 支持 MySQL, PostgreSQL
|
||
|
|
DATABASE_URL = os.getenv(
|
||
|
|
"DATABASE_URL",
|
||
|
|
"postgresql://postgres:postgres@localhost:5432/zodiac"
|
||
|
|
)
|
||
|
|
|
||
|
|
# 数据库引擎配置
|
||
|
|
engine = create_engine(
|
||
|
|
DATABASE_URL,
|
||
|
|
pool_pre_ping=True,
|
||
|
|
pool_size=10,
|
||
|
|
max_overflow=20,
|
||
|
|
echo=False
|
||
|
|
)
|
||
|
|
|
||
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||
|
|
|
||
|
|
Base = declarative_base()
|
||
|
|
|
||
|
|
|
||
|
|
def get_db():
|
||
|
|
"""获取数据库会话"""
|
||
|
|
db = SessionLocal()
|
||
|
|
try:
|
||
|
|
yield db
|
||
|
|
finally:
|
||
|
|
db.close()
|