db867dcbe5
Deploy to Staging / deploy (push) Has been cancelled
Conflict detector / main (push) Has been cancelled
Lint Backend / lint-backend (push) Has been cancelled
Playwright Tests / changes (push) Has been cancelled
Test Backend / test-backend (push) Has been cancelled
Test Docker Compose / test-docker-compose (push) Has been cancelled
Playwright Tests / test-playwright (1, 4) (push) Has been cancelled
Playwright Tests / test-playwright (2, 4) (push) Has been cancelled
Playwright Tests / test-playwright (3, 4) (push) Has been cancelled
Playwright Tests / test-playwright (4, 4) (push) Has been cancelled
Playwright Tests / merge-playwright-reports (push) Has been cancelled
Playwright Tests / alls-green-playwright (push) Has been cancelled
Issue Manager / issue-manager (push) Has been cancelled
33 lines
1.1 KiB
Python
33 lines
1.1 KiB
Python
from sqlmodel import Session, create_engine, select
|
||
|
||
from app import crud
|
||
from app.core.config import settings
|
||
from app.models import User, UserCreate
|
||
|
||
engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
|
||
|
||
|
||
# 确保在初始化数据库之前已导入所有 SQLModel 模型(app.models)
|
||
# 否则,SQLModel 可能无法正确初始化关系
|
||
# 更多详情请参考:https://github.com/fastapi/full-stack-fastapi-template/issues/28
|
||
|
||
|
||
def init_db(session: Session) -> None:
|
||
# 数据库表应该通过 Alembic 迁移创建
|
||
# 但如果你不想使用迁移,可以取消注释下面的代码来创建表
|
||
# from sqlmodel import SQLModel
|
||
|
||
# 这样可以正常工作,因为模型已经从 app.models 导入并注册
|
||
# SQLModel.metadata.create_all(engine)
|
||
|
||
user = session.exec(
|
||
select(User).where(User.email == settings.FIRST_SUPERUSER)
|
||
).first()
|
||
if not user:
|
||
user_in = UserCreate(
|
||
email=settings.FIRST_SUPERUSER,
|
||
password=settings.FIRST_SUPERUSER_PASSWORD,
|
||
is_superuser=True,
|
||
)
|
||
user = crud.create_user(session=session, user_create=user_in)
|