38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
from pathlib import Path
|
|
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
from sqlalchemy import select
|
|
|
|
from app.config import BACKEND_ROOT, admin_password, admin_username
|
|
from app.db import session_scope
|
|
from app.models import AppSetting, User
|
|
from app.security import hash_password
|
|
|
|
logger = logging.getLogger("decom")
|
|
|
|
|
|
def init_db() -> None:
|
|
from app.config import DATA_DIR
|
|
|
|
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
config = Config(str(Path(BACKEND_ROOT) / "alembic.ini"))
|
|
config.set_main_option("script_location", str(Path(BACKEND_ROOT) / "alembic"))
|
|
command.upgrade(config, "head")
|
|
with session_scope() as session:
|
|
if session.get(AppSetting, 1) is None:
|
|
session.add(AppSetting(id=1, login_mode="local", credential_refresh_seconds=300))
|
|
if admin_username() and admin_password() and session.scalar(select(User).where(User.role == "admin")) is None:
|
|
session.add(
|
|
User(
|
|
username=admin_username(),
|
|
password_hash=hash_password(admin_password()),
|
|
role="admin",
|
|
)
|
|
)
|
|
logger.info("已创建管理员 %s", admin_username())
|