init_db.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from sqlalchemy import create_engine
  4. from sqlalchemy.orm import Session, sessionmaker
  5. from core.config import settings
  6. from core.security import hashed_password
  7. from crud.base import CRUDBase
  8. from models.user import SysUser
  9. from schemas.user import CreateAdminUser
  10. class Crud(CRUDBase):
  11. def create(self, db: Session, user: CreateAdminUser):
  12. db_obj = SysUser(username=user.username,
  13. password=hashed_password(user.password),
  14. phone=user.phone,
  15. role_id=user.role_id,
  16. last_login_time=user.last_login_time,
  17. last_login_ip=user.last_login_ip)
  18. db.add(db_obj)
  19. db.commit()
  20. db.refresh(db_obj)
  21. return user
  22. def init_db(db: Session) -> None:
  23. # admin
  24. crud_admin = Crud(SysUser)
  25. admin = CreateAdminUser(username=settings.ADMIN_USERNAME,
  26. password=settings.ADMIN_PASSWORD,
  27. phone="13579246810",
  28. role_id=settings.ADMIN_ROLE_ID)
  29. crud_admin.create(db, admin)
  30. # permission
  31. # enforcer = get_enforcer()
  32. # enforcer.add_permission_for_user("*", "/*", "*")
  33. if __name__ == '__main__':
  34. engine = create_engine(settings.SYNC_MYSQL_URI, pool_pre_ping=True)
  35. SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  36. db = SessionLocal()
  37. init_db(db)