85 lines
2.4 KiB
Python
85 lines
2.4 KiB
Python
"""
|
|
FastAPI Application Handler Module
|
|
|
|
This module contains all the handler functions for configuring and setting up the FastAPI application:
|
|
- CORS middleware configuration
|
|
- Exception handlers setup
|
|
- Uvicorn server configuration
|
|
"""
|
|
|
|
from fastapi import FastAPI, Request, status
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from pydantic import ValidationError
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from ApiLayers.ErrorHandlers.ErrorHandlers.api_exc_handler import (
|
|
HTTPExceptionApiHandler,
|
|
validation_exception_handler,
|
|
)
|
|
from ApiLayers.ErrorHandlers.Exceptions.api_exc import HTTPExceptionApi
|
|
from ApiLayers.Middleware.auth_middleware import (
|
|
RequestTimingMiddleware,
|
|
LoggerTimingMiddleware,
|
|
)
|
|
|
|
|
|
def setup_cors_middleware(app: FastAPI) -> None:
|
|
"""
|
|
Configure CORS middleware for the application.
|
|
|
|
Args:
|
|
app: FastAPI application instance
|
|
"""
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["http://localhost:3000", "*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
async def generic_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
|
"""
|
|
Handle generic exceptions and return formatted error responses.
|
|
|
|
Args:
|
|
request: FastAPI request object
|
|
exc: Exception instance
|
|
|
|
Returns:
|
|
JSONResponse: Formatted error response
|
|
"""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
content={"detail": "Internal server error", "error_code": "INTERNAL_ERROR"},
|
|
)
|
|
|
|
|
|
def setup_exception_handlers(app: FastAPI) -> None:
|
|
"""
|
|
Configure custom exception handlers for the application.
|
|
|
|
Args:
|
|
app: FastAPI application instance
|
|
"""
|
|
custom_exception_handler = HTTPExceptionApiHandler(response_model=JSONResponse)
|
|
app.add_exception_handler(ValidationError, validation_exception_handler)
|
|
app.add_exception_handler(
|
|
HTTPExceptionApi, custom_exception_handler.handle_exception
|
|
)
|
|
app.add_exception_handler(Exception, generic_exception_handler)
|
|
|
|
|
|
def setup_middleware(app: FastAPI) -> None:
|
|
"""
|
|
Configure all middleware for the application.
|
|
|
|
Args:
|
|
app: FastAPI application instance
|
|
"""
|
|
setup_cors_middleware(app)
|
|
app.add_middleware(RequestTimingMiddleware)
|
|
app.add_middleware(LoggerTimingMiddleware)
|
|
setup_exception_handlers(app)
|