init_db.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from sqlalchemy.orm import Session
  2. from app import crud, schemas
  3. from app.core.config import settings
  4. from app.db import base # noqa: F401
  5. from app.models.enum import Membership, Progress
  6. from sqlalchemy.ext.declarative import declarative_base
  7. from sqlalchemy import create_engine
  8. # make sure all SQL Alchemy models are imported (app.db.base) before initializing DB
  9. # otherwise, SQL Alchemy might fail to initialize relationships properly
  10. # for more details: https://github.com/tiangolo/full-stack-fastapi-postgresql/issues/28
  11. def init_db(db: Session) -> None:
  12. # Tables should be created with Alembic migrations
  13. # But if you don't want to use migrations, create
  14. # the tables un-commenting the next line
  15. '''
  16. Base = declarative_base()
  17. #Base.query = db.query_property()
  18. '''
  19. user = "choozmo"
  20. password = "pAssw0rd"
  21. host = "db.ptt.cx:3306"
  22. db_name = "video_maker"
  23. engine = create_engine(f'mysql://{user}:{password}@{host}/{db_name}', pool_pre_ping=True)
  24. base.Base.metadata.create_all(bind=engine)
  25. if settings.MEMBERSHIP_STATUS:
  26. for STATUS in settings.MEMBERSHIP_STATUS:
  27. if not db.query(Membership).filter(Membership.status == STATUS).first():
  28. db.add(Membership(status=STATUS))
  29. db.commit()
  30. if settings.PROGRESS_STATE:
  31. for STATE in settings.PROGRESS_STATE:
  32. if not db.query(Progress).filter(Progress.state == STATE).first():
  33. db.add(Progress(state=STATE))
  34. db.commit()
  35. user = crud.user.get_by_email(db, email=settings.FIRST_SUPERUSER)
  36. if not user:
  37. user_in = schemas.UserCreate(
  38. email=settings.FIRST_SUPERUSER,
  39. password=settings.FIRST_SUPERUSER_PASSWORD,
  40. is_superuser=True,
  41. )
  42. user = crud.user.create(db, obj_in=user_in) # noqa: F841