Spaces:
Running
Running
Download src/app.py from reputeradar/ioc-core: direct link, hf CLI and curl.
- Browser
- Download file 3.41 kB
-
https://huggingface.co/spaces/reputeradar/ioc-core/resolve/main/src/app.py
- Command line
-
hf download hf://spaces/reputeradar/ioc-core/src/app.py
-
curl -L -o app.py https://huggingface.co/spaces/reputeradar/ioc-core/resolve/main/src/app.py
3.41 kB
| """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__) | |
| 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) | |
| 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() | |