Files
eventspace/backend/app/init_db.py
Felipe Cardoso fee7d8b5ec Refactor CRUD module imports and usage for clarity.
Replaces ambiguous shorthand references like `event` and `user` with more descriptive names such as `event_crud` and `user_crud`. Updates imports, function calls, tests, and other references across the codebase to maintain consistency. This improves code readability and reduces potential confusion.
2025-03-15 01:22:04 +01:00

53 lines
1.6 KiB
Python

# app/core/init_db.py
import logging
from typing import Optional
from sqlalchemy.orm import Session
from app.core.config import settings
from app.crud.user import user_crud as user_crud
from app.schemas.users import UserCreate
from app.core.database import engine
logger = logging.getLogger(__name__)
def init_db(db: Session) -> Optional[UserCreate]:
"""
Initialize database with first superuser if settings are configured and user doesn't exist.
"""
if not settings.FIRST_SUPERUSER_EMAIL or not settings.FIRST_SUPERUSER_PASSWORD:
logger.warning("First superuser credentials not configured in settings")
return None
try:
# Check if superuser already exists
existing_user = user_crud.get_by_email(
db, email=settings.FIRST_SUPERUSER_EMAIL
)
if existing_user:
logger.info("Superuser already exists, skipping creation")
return None
# Create superuser if doesn't exist
user_in = UserCreate(
email=settings.FIRST_SUPERUSER_EMAIL,
password=settings.FIRST_SUPERUSER_PASSWORD,
first_name="Admin", # Required by your schema
last_name="User", # Required by your schema
is_superuser=True
)
user = user_crud.create(db, obj_in=user_in)
logger.info(f"Created first superuser: {user.email}")
return user
except Exception as e:
logger.error(f"Error creating superuser: {e}")
raise
if __name__ == "__main__":
with Session(engine) as session:
try:
init_db(session)
finally:
session.close()