initial_data.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. import asyncio
  7. from sqlalchemy import select
  8. from app.core import config, security
  9. from app.core.session import session
  10. from app.models import User
  11. async def main() -> None:
  12. print("Start initial data")
  13. with session() as db:
  14. result = db.execute(
  15. select(User).where(User.email == config.settings.FIRST_SUPERUSER_EMAIL)
  16. )
  17. user = result.scalars().first()
  18. if user is None:
  19. new_superuser = User(
  20. email=config.settings.FIRST_SUPERUSER_EMAIL,
  21. hashed_password=security.get_password_hash(
  22. config.settings.FIRST_SUPERUSER_PASSWORD
  23. ),
  24. )
  25. db.add(new_superuser)
  26. db.commit()
  27. print("Superuser was created")
  28. else:
  29. print("Superuser already exists in database")
  30. print("Initial data created")
  31. if __name__ == "__main__":
  32. asyncio.run(main())