初步增加 web 界面
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
"""数据库引擎与会话管理"""
|
||||
|
||||
from pathlib import Path
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
DB_PATH = Path(__file__).parent.parent.parent / "data" / "web.db"
|
||||
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
engine = create_engine(
|
||||
f"sqlite:///{DB_PATH}",
|
||||
connect_args={"check_same_thread": False},
|
||||
echo=False,
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db():
|
||||
"""FastAPI 依赖:提供数据库会话,请求结束自动关闭。"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""建表 + 写入初始数据。"""
|
||||
Base.metadata.create_all(bind=engine)
|
||||
_seed()
|
||||
|
||||
|
||||
def _seed():
|
||||
"""写入默认超管账号和角色。"""
|
||||
from .models import User
|
||||
from .security import hash_password
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
if not db.query(User).first():
|
||||
admin = User(
|
||||
username="admin",
|
||||
password_hash=hash_password("admin123"),
|
||||
role="super_admin",
|
||||
is_active=True,
|
||||
remark="默认超级管理员",
|
||||
)
|
||||
db.add(admin)
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
Reference in New Issue
Block a user