File size: 3,671 Bytes
35cd1bc 1aed450 35cd1bc 1aed450 5423b05 35cd1bc 1aed450 35cd1bc c57e8be 35cd1bc e76ae0b 35cd1bc | 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 | from contextlib import asynccontextmanager
from typing import AsyncGenerator
import logging
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from .routes.tasks import router as tasks_router
from .routes.auth import router as auth_router
from .routes.chat import router as chat_router
from .mcp_server import server as mcp_server
from ..config import settings
from ..utils.error_handlers import add_exception_handlers
from ..middleware.security import SecurityHeadersMiddleware
# Reduce SQLAlchemy logging to reduce noise
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
logging.getLogger('sqlalchemy.dialects').setLevel(logging.WARNING)
logging.getLogger('sqlalchemy.pool').setLevel(logging.WARNING)
logging.getLogger('sqlalchemy.orm').setLevel(logging.WARNING)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""
Lifespan event handler for FastAPI application.
Handles startup and shutdown events.
"""
# Startup
print("Starting up Todo Backend API...")
# Add exception handlers
add_exception_handlers(app)
yield
# Shutdown
print("Shutting down Todo Backend API...")
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 CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://localhost:3001",
"http://127.0.0.1:3001",
"https://frntend-hugging.vercel.app", # Vercel frontend URL
"https://frntend-hugging-ecq4wpld6-asma-akbar-raos-projects.vercel.app", # Specific Vercel deployment URL
"https://asmaakbar-phase-iii.hf.space", # Hugging Face Space URL
"https://*.hf.space" # Wildcard for Hugging Face Spaces
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Middleware to handle HTTPS protocol when behind a proxy/load balancer
@app.middleware("http")
async def https_middleware(request: Request, call_next):
# Check if the request came through HTTPS via proxy headers
if request.headers.get("x-forwarded-proto") == "https":
request.scope["scheme"] = "https"
elif request.headers.get("x-forwarded-proto") == "http":
request.scope["scheme"] = "http"
response = await call_next(request)
return response
# Include API routes
app.include_router(tasks_router, prefix=settings.api_prefix)
app.include_router(auth_router, prefix=settings.api_prefix)
app.include_router(chat_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",
"status": "running",
"endpoints": {
"api_docs": "/docs",
"redoc": "/redoc",
"chat": f"{settings.api_prefix}/chat/{{user_id}}/chat"
}
}
return app
app = create_app()
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"src.api.main:app",
host="0.0.0.0",
port=8000,
reload=True
) |