初始提交:极码 GeekCode 全栈项目(FastAPI + Vue3)
This commit is contained in:
34
backend/database.py
Normal file
34
backend/database.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""数据库连接配置"""
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from config import DATABASE_URL
|
||||
|
||||
# 根据数据库类型配置引擎参数
|
||||
if "sqlite" in DATABASE_URL:
|
||||
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
|
||||
else:
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
pool_size=10,
|
||||
max_overflow=20,
|
||||
pool_recycle=3600,
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db():
|
||||
"""获取数据库会话的依赖注入"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""初始化数据库,创建所有表"""
|
||||
Base.metadata.create_all(bind=engine)
|
||||
Reference in New Issue
Block a user