# app/core/lifespan.py """Summary description .... This module provides classes and functions for: - .... - .... - .... """ import logging from contextlib import asynccontextmanager from fastapi import FastAPI from sqlalchemy import text from middleware.auth import AuthManager 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.""" # Startup app_logger = setup_logging() # Configure logging first app_logger.info("Starting up ecommerce API") # Create tables Base.metadata.create_all(bind=engine) # Create indexes create_indexes() # Create default admin user db = SessionLocal() try: auth_manager.create_default_admin_user(db) except Exception as e: logger.error(f"Failed to create default admin user: {e}") finally: db.close() yield # Shutdown app_logger.info("Shutting down ecommerce API") def create_indexes(): """Create database indexes.""" with engine.connect() as conn: try: # User indexes conn.execute( text("CREATE INDEX IF NOT EXISTS idx_user_email ON users(email)") ) conn.execute( text("CREATE INDEX IF NOT EXISTS idx_user_username ON users(username)") ) # Product indexes conn.execute( text("CREATE INDEX IF NOT EXISTS idx_product_gtin ON products(gtin)") ) conn.execute( text( "CREATE INDEX IF NOT EXISTS idx_product_marketplace ON products(marketplace)" ) ) # Stock indexes conn.execute( text( "CREATE INDEX IF NOT EXISTS idx_stock_gtin_location ON stock(gtin, location)" ) ) conn.commit() logger.info("Database indexes created successfully") except Exception as e: logger.warning(f"Index creation warning: {e}")