initial_data.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. """
  2. Put here any Python code that must be runned before application startup.
  3. It is included in `init.sh` script.
  4. By defualt `main` create a superuser if not exists
  5. """
  6. from sqlalchemy import select
  7. from app.core import config, security
  8. from app.core.session import session
  9. from app.models import GlobalRole, User
  10. def main() -> None:
  11. print("Start initial data")
  12. with session() as db:
  13. result = db.execute(select(User).where(User.email == config.settings.FIRST_SUPERUSER_EMAIL))
  14. user = result.scalars().first()
  15. if user is None:
  16. new_superuser = User(
  17. email=config.settings.FIRST_SUPERUSER_EMAIL,
  18. hashed_password=security.get_password_hash(
  19. config.settings.FIRST_SUPERUSER_PASSWORD
  20. ),
  21. global_role=GlobalRole.SUPER_ADMIN,
  22. )
  23. db.add(new_superuser)
  24. print("Superuser was created")
  25. else:
  26. print("Superuser already exists in database")
  27. user.global_role = GlobalRole.SUPER_ADMIN
  28. db.commit()
  29. print("Initial data created")
  30. if __name__ == "__main__":
  31. main()