71 lines
2.5 KiB
Python
71 lines
2.5 KiB
Python
"""初始化数据库:建库 + 建表 + 建初始管理员。
|
|
|
|
用法:
|
|
python -m app.scripts.init_db # 建表(不会删数据)
|
|
python -m app.scripts.init_db --drop # 先删表再建(危险,会清空数据)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import sys
|
|
|
|
from app.core.config import settings
|
|
from app.core.database import SessionLocal, engine, ensure_database_exists
|
|
from app.core.security import hash_password
|
|
from app.dao.account_dao import AccountDao
|
|
from app.model import Account, Base, Role
|
|
|
|
|
|
def init(drop: bool = False) -> None:
|
|
ensure_database_exists()
|
|
if drop:
|
|
confirm = input("这会删除 wolin 库里的全部表和数据,输入 yes 继续:")
|
|
if confirm.strip().lower() != "yes":
|
|
print("已取消")
|
|
return
|
|
Base.metadata.drop_all(bind=engine)
|
|
print("已删除所有表")
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
tables = ", ".join(sorted(Base.metadata.tables.keys()))
|
|
print(f"建表完成:{tables}")
|
|
|
|
with SessionLocal() as db:
|
|
if AccountDao.get_by_username(db, settings.ADMIN_USERNAME, with_deleted=True) is None:
|
|
db.add(
|
|
Account(
|
|
username=settings.ADMIN_USERNAME,
|
|
hashed_password=hash_password(settings.ADMIN_PASSWORD),
|
|
real_name="系统管理员",
|
|
role=Role.ADMIN.value,
|
|
)
|
|
)
|
|
db.commit()
|
|
print(f"初始管理员:{settings.ADMIN_USERNAME} / {settings.ADMIN_PASSWORD}")
|
|
else:
|
|
print(f"管理员 {settings.ADMIN_USERNAME} 已存在,跳过")
|
|
|
|
if AccountDao.get_by_username(db, "viewer", with_deleted=True) is None:
|
|
db.add(
|
|
Account(
|
|
username="viewer",
|
|
hashed_password=hash_password("viewer123"),
|
|
real_name="只读访客",
|
|
role=Role.VIEWER.value,
|
|
)
|
|
)
|
|
db.commit()
|
|
print("只读账号:viewer / viewer123")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(description="初始化沃林学生管理系统数据库")
|
|
parser.add_argument("--drop", action="store_true", help="先删除所有表再重建(会丢数据)")
|
|
args = parser.parse_args()
|
|
try:
|
|
init(drop=args.drop)
|
|
except Exception as exc: # noqa: BLE001
|
|
print(f"初始化失败:{exc}", file=sys.stderr)
|
|
raise
|