db.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from app.config import settings
  2. from app.models import crud
  3. from app.models.user import User, UserCreate
  4. from sqlmodel import Session, SQLModel, create_engine, select
  5. # postgres
  6. engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
  7. async def initiate_nongo():
  8. client = AsyncIOMotorClient(Settings().DATABASE_URL)
  9. await init_beanie(
  10. database=client.get_default_database(), document_models=models.__all__
  11. )
  12. async def initate_postgres(session: Session) -> None:
  13. """
  14. init db
  15. :param session: database session
  16. """
  17. # Base.metadata.create_all(bind=engine)
  18. SQLModel.metadata.create_all(bind=engine)
  19. user = session.exec(
  20. select(User).where(User.email == settings.FIRST_SUPERUSER)
  21. ).first()
  22. # 插入管理员账户
  23. if not user:
  24. user_in = UserCreate(
  25. email=settings.FIRST_SUPERUSER,
  26. password=settings.FIRST_SUPERUSER_PASSWORD,
  27. is_superuser=True,
  28. )
  29. user = crud.create_user(session=session, user_create=user_in)
  30. async def initate_redis():
  31. await init_redis(app=app, settings=settings)
  32. async def initate_sqlite():
  33. await init_sqlite(app=app, settings=settings)