132 lines
3.8 KiB
Python
132 lines
3.8 KiB
Python
# app/core/lifespan.py
|
|
"""Application lifespan management - Clean Migration Approach.
|
|
|
|
This module provides classes and functions for:
|
|
- Application startup and shutdown events
|
|
- Logging setup
|
|
- Default user creation
|
|
- NO database table creation (handled by Alembic)
|
|
"""
|
|
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI
|
|
from sqlalchemy import text
|
|
|
|
from middleware.auth import AuthManager
|
|
# Remove this import if not needed: from models.database.base import Base
|
|
|
|
from .database import SessionLocal, engine
|
|
from .logging import setup_logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
auth_manager = AuthManager()
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""Application lifespan events - Clean migration approach."""
|
|
|
|
# === STARTUP ===
|
|
app_logger = setup_logging()
|
|
app_logger.info("Starting up ecommerce API")
|
|
|
|
# === REMOVED: Database table creation ===
|
|
# Base.metadata.create_all(bind=engine) # ❌ Removed - handled by Alembic
|
|
# create_indexes() # ❌ Removed - handled by Alembic
|
|
|
|
# === KEPT: Application-level initialization ===
|
|
|
|
# Create default admin user (after migrations have run)
|
|
db = SessionLocal()
|
|
try:
|
|
auth_manager.create_default_admin_user(db)
|
|
logger.info("Default admin user initialization completed")
|
|
except Exception as e:
|
|
logger.error(f"Failed to create default admin user: {e}")
|
|
# In development, this might fail if tables don't exist yet
|
|
# That's OK - migrations should be run separately
|
|
finally:
|
|
db.close()
|
|
|
|
# Add any other application-level initialization here
|
|
# Examples:
|
|
# - Load configuration
|
|
# - Initialize caches
|
|
# - Set up external service connections
|
|
# - Load initial data (AFTER migrations)
|
|
|
|
logger.info("✅ Application startup completed")
|
|
|
|
yield
|
|
|
|
# === SHUTDOWN ===
|
|
app_logger.info("Shutting down ecommerce API")
|
|
# Add cleanup tasks here if needed
|
|
|
|
|
|
# === REMOVED FUNCTION ===
|
|
# def create_indexes():
|
|
# """Create database indexes."""
|
|
# # This is now handled by Alembic migrations
|
|
# pass
|
|
|
|
|
|
# === NEW HELPER FUNCTION ===
|
|
def check_database_ready():
|
|
"""Check if database is ready (migrations have been run)."""
|
|
try:
|
|
with engine.connect() as conn:
|
|
# Try to query a table that should exist
|
|
result = conn.execute(text("SELECT name FROM sqlite_master WHERE type='table' LIMIT 1"))
|
|
tables = result.fetchall()
|
|
return len(tables) > 0
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def get_migration_status():
|
|
"""Get current Alembic migration status."""
|
|
try:
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
|
|
alembic_cfg = Config("alembic.ini")
|
|
|
|
# This would need more implementation to actually check status
|
|
# For now, just return a placeholder
|
|
return "Migration status check not implemented"
|
|
except Exception as e:
|
|
logger.warning(f"Could not check migration status: {e}")
|
|
return "Unknown"
|
|
|
|
|
|
# === STARTUP VERIFICATION (Optional) ===
|
|
def verify_startup_requirements():
|
|
"""Verify that all startup requirements are met."""
|
|
|
|
issues = []
|
|
|
|
# Check if database exists and has tables
|
|
if not check_database_ready():
|
|
issues.append("Database not ready - run 'make migrate-up' first")
|
|
|
|
# Add other checks as needed
|
|
# - Configuration validation
|
|
# - External service connectivity
|
|
# - Required environment variables
|
|
|
|
if issues:
|
|
logger.error("❌ Startup verification failed:")
|
|
for issue in issues:
|
|
logger.error(f" - {issue}")
|
|
return False
|
|
|
|
logger.info("✅ Startup verification passed")
|
|
return True
|
|
|
|
# You can call this in your main.py if desired:
|
|
# if not verify_startup_requirements():
|
|
# raise RuntimeError("Application startup requirements not met")
|