import os from contextlib import asynccontextmanager from typing import AsyncGenerator from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette.middleware.trustedhost import TrustedHostMiddleware from .routes.tasks import router as tasks_router from .routes.auth import router as auth_router from ..config import settings from ..utils.error_handlers import add_exception_handlers from ..middleware.security import SecurityHeadersMiddleware from sqlmodel import SQLModel from ..database.database import sync_engine from ..models.user import User from ..models.task import Task @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: """ Lifespan event handler for FastAPI application. Handles startup and shutdown events. """ # Startup # Create database tables SQLModel.metadata.create_all(bind=sync_engine) # Add exception handlers add_exception_handlers(app) yield # Shutdown def create_app() -> FastAPI: """ Create and configure the FastAPI application. Returns: Configured FastAPI application instance """ app = FastAPI( title=settings.app_name, debug=settings.debug, lifespan=lifespan ) # Add security headers middleware first app.add_middleware(SecurityHeadersMiddleware) # Add custom middleware to handle HTTPS redirects properly in proxy environments like Hugging Face Spaces # This handles forwarded headers (X-Forwarded-Proto, X-Forwarded-Host, etc.) # which is essential when running behind a proxy/load balancer like Hugging Face @app.middleware("http") async def https_redirect_middleware(request, call_next): # Handle X-Forwarded-Proto header to preserve HTTPS when behind proxy/load balancer if request.headers.get("x-forwarded-proto") == "https": request.scope["scheme"] = "https" response = await call_next(request) return response # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=[ "https://frontend-hugging.vercel.app", "https://frontend-hugging-myidyjvtn-asma-akbar-raos-projects.vercel.app", # Current Vercel deployment URL "https://asmaakbar-phase-ll.hf.space", # Hugging Face Space URL "http://localhost:3000", # For local development "http://localhost:8000", # For local backend settings.frontend_url, # Use configured frontend URL from settings ], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include API routes app.include_router(tasks_router, prefix=settings.api_prefix) app.include_router(auth_router, prefix=settings.api_prefix) @app.get("/") async def root(): """Root endpoint for the API.""" return { "message": "Welcome to the Todo Backend API", "app_name": settings.app_name, "version": "1.0.0" } return app app = create_app() if __name__ == "__main__": import uvicorn uvicorn.run( "backend.src.api.main:app", host="0.0.0.0", port=8000, reload=True )