You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
1.1 KiB
42 lines
1.1 KiB
"""
|
|
数据库连接和会话管理
|
|
"""
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.orm.session import Session
|
|
from backend.config import get_database_url,DATABASE_CONFIG
|
|
|
|
# 创建数据库引擎
|
|
engine = create_engine(
|
|
get_database_url(),
|
|
pool_pre_ping=True,
|
|
pool_recycle=3600,
|
|
echo=False # 设置为True可以看到SQL语句
|
|
)
|
|
|
|
# 创建会话工厂
|
|
SessionLocal: sessionmaker[Session] = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# 声明基类
|
|
Base = declarative_base()
|
|
|
|
def get_db():
|
|
"""获取数据库会话"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
def init_db():
|
|
"""初始化数据库表"""
|
|
from backend.models import Student, RollCallRecord, ScoreRecord
|
|
from os import getenv
|
|
if(mod:=getenv("DEV_MOD","DEV")):
|
|
if(mod=="TEST"):
|
|
Base.metadata.drop_all(bind=engine)
|
|
print("已清空测试数据库表")
|
|
Base.metadata.create_all(bind=engine)
|
|
|