Spaces:
Running
Running
File size: 3,405 Bytes
90531db 7fddf3d 90531db 567eb03 54559aa 567eb03 54559aa 567eb03 9dce235 54559aa 567eb03 54559aa 567eb03 54559aa 567eb03 54559aa 567eb03 54559aa 567eb03 54559aa 567eb03 54559aa 567eb03 54559aa 567eb03 90531db 4b83c9c 90531db | 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 | """Main FastAPI application factory and configuration."""
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from src import __description__, __version__
from src.api import create_api_router
from src.config import settings
from src.logging_config import setup_logging
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Application lifespan manager.
Handles startup and shutdown events.
"""
# Startup
logger.info(f"Starting IOC Core API v{__version__}")
# Log API key status
api_keys = settings.validate_api_keys()
logger.info(f"API Key Status: {api_keys}")
if not all(api_keys.values()):
logger.warning("Some API keys are not configured. Some endpoints may not work.")
yield
# Shutdown
logger.info("Shutting down IOC Core API")
def create_app() -> FastAPI:
"""
Create and configure the FastAPI application.
Returns:
Configured FastAPI application instance
"""
# Setup logging
setup_logging()
# Create FastAPI app
app = FastAPI(
title=settings.APP_NAME,
description=__description__,
version=__version__,
lifespan=lifespan,
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Request ID middleware for request tracing
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from src.logging_config import set_request_id
class RequestIdMiddleware(BaseHTTPMiddleware):
"""Add unique request ID to each request for log correlation."""
# Paths to skip logging (reduce noise)
SKIP_LOG_PATHS = {"/", "/favicon.ico", "/api/health"}
async def dispatch(self, request: Request, call_next):
# Generate or use existing request ID
request_id = request.headers.get("X-Request-ID") or None
request_id = set_request_id(request_id)
# Check if we should log this request
should_log = request.url.path not in self.SKIP_LOG_PATHS
if should_log:
logger.info(f"→ {request.method} {request.url.path}")
import time
start_time = time.time()
response = await call_next(request)
# Log request end with duration
if should_log:
duration_ms = (time.time() - start_time) * 1000
logger.info(f"← {request.method} {request.url.path} -> {response.status_code} ({duration_ms:.0f}ms)")
# Add request ID to response headers
response.headers["X-Request-ID"] = request_id
return response
app.add_middleware(RequestIdMiddleware)
# Include API routers
api_router = create_api_router()
app.include_router(api_router)
@app.get("/", tags=["Health"])
async def root():
return {"message": "IOC Core API is running", "docs": "/docs"}
logger.info("FastAPI application created successfully")
return app
# Create app instance
app = create_app()
|