File size: 3,766 Bytes
8e73bed 90ad38a 8e73bed 90ad38a 8e73bed |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
"""
FastAPI Main Application
"""
import sys
import os
from pathlib import Path
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from loguru import logger
from app.config import settings
from app.core.redis_client import get_redis_client
from app.api.routes import router
# Configure logging
logger.remove()
logger.add(
sys.stdout,
format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan> - <level>{message}</level>",
level=settings.LOG_LEVEL
)
# Create logs directory if it doesn't exist
try:
log_dir = Path("logs")
log_dir.mkdir(parents=True, exist_ok=True)
logger.add(
"logs/swara_api_{time:YYYY-MM-DD}.log",
rotation="1 day",
retention="7 days",
format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function} - {message}",
level=settings.LOG_LEVEL
)
except (PermissionError, OSError) as e:
# If we can't write to logs directory, only use stdout
logger.warning(f"Cannot create log file: {e}. Using stdout only.")
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Application lifespan events
"""
# Startup
logger.info("=" * 70)
logger.info("π SWARA API Starting...")
logger.info("=" * 70)
logger.info(f"Environment: {settings.ENV}")
logger.info(f"API Version: {settings.API_VERSION}")
logger.info(f"Redis URL: {settings.REDIS_URL}")
# Connect to Redis
try:
redis_client = get_redis_client()
redis_client.connect()
logger.info("β Redis connection established")
except Exception as e:
logger.error(f"β Failed to connect to Redis: {e}")
logger.warning("β API will start but background tasks will not work")
# Create necessary directories
settings.get_temp_dir()
settings.get_models_dir()
logger.info("β Directories created")
logger.info("=" * 70)
logger.info(f"β SWARA API Ready at http://{settings.API_HOST}:{settings.API_PORT}")
logger.info("=" * 70)
yield
# Shutdown
logger.info("=" * 70)
logger.info("π SWARA API Shutting down...")
logger.info("=" * 70)
# Disconnect from Redis
try:
redis_client = get_redis_client()
redis_client.disconnect()
logger.info("β Redis disconnected")
except:
pass
logger.info("β Shutdown complete")
logger.info("=" * 70)
# Create FastAPI application
app = FastAPI(
title=settings.API_TITLE,
version=settings.API_VERSION,
description=settings.API_DESCRIPTION,
lifespan=lifespan,
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json"
)
# CORS Middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, specify allowed origins
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(router)
# Global exception handler
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
"""Global exception handler"""
logger.error(f"Unhandled exception: {exc}")
return JSONResponse(
status_code=500,
content={
"error": "Internal server error",
"detail": str(exc) if settings.ENV == "development" else "An unexpected error occurred"
}
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app.main:app",
host=settings.API_HOST,
port=settings.API_PORT,
reload=settings.ENV == "development",
workers=settings.API_WORKERS
)
|