Spaces:
Runtime error
Runtime error
Download main.py from MaheenGhouri/fullstack_todo_app: direct link, hf CLI and curl.
- Browser
- Download file 3.4 kB
-
https://huggingface.co/spaces/MaheenGhouri/fullstack_todo_app/resolve/main/main.py
- Command line
-
hf download hf://spaces/MaheenGhouri/fullstack_todo_app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/MaheenGhouri/fullstack_todo_app/resolve/main/main.py
3.4 kB
| import sys | |
| import os | |
| # Add current directory to path for imports since running in container | |
| current_dir = os.path.dirname(os.path.abspath(__file__)) | |
| if current_dir not in sys.path: | |
| sys.path.insert(0, current_dir) | |
| # Load environment variables from .env file | |
| from dotenv import load_dotenv | |
| load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')) | |
| import logging | |
| from fastapi import FastAPI, Depends, Request, HTTPException | |
| from fastapi.responses import JSONResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.middleware import Middleware | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.requests import Request | |
| from starlette.responses import Response | |
| from starlette.background import BackgroundTask | |
| import time | |
| # Import routes using absolute imports | |
| from routes import auth, tasks, health, chat | |
| import os | |
| # Set up logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| def validate_environment(): | |
| """Validate required environment variables at startup""" | |
| required_vars = ["BETTER_AUTH_SECRET"] | |
| missing_vars = [] | |
| for var in required_vars: | |
| if not os.getenv(var): | |
| missing_vars.append(var) | |
| if missing_vars: | |
| logger.error(f"Missing required environment variables: {', '.join(missing_vars)}") | |
| raise ValueError(f"Missing required environment variables: {', '.join(missing_vars)}") | |
| logger.info("Environment validation passed") | |
| # Validate environment at startup | |
| validate_environment() | |
| app = FastAPI(title="Todo App Backend", version="1.0.0") | |
| class LoggingMiddleware(BaseHTTPMiddleware): | |
| async def dispatch(self, request: Request, call_next): | |
| start_time = time.time() | |
| # Log request | |
| logger.info(f"Request: {request.method} {request.url}") | |
| response = await call_next(request) | |
| # Log response | |
| process_time = time.time() - start_time | |
| logger.info(f"Response: {response.status_code} in {process_time:.2f}s") | |
| return response | |
| # Add logging middleware | |
| app.add_middleware(LoggingMiddleware) | |
| # CORS configuration - allow multiple frontend ports for development | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=[ | |
| "http://localhost:3000", | |
| "http://localhost:3001", | |
| "http://127.0.0.1:3000", | |
| "http://127.0.0.1:3001", | |
| ], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Global exception handler for better error messages | |
| async def global_exception_handler(request: Request, exc: Exception): | |
| logger.error(f"Unhandled exception: {exc}", exc_info=True) | |
| return JSONResponse( | |
| status_code=500, | |
| content={"detail": str(exc) if hasattr(exc, 'detail') else "Internal server error"} | |
| ) | |
| # Include routes | |
| app.include_router(auth.router, prefix="/api/auth", tags=["auth"]) | |
| app.include_router(tasks.router, prefix="/api/tasks", tags=["tasks"]) | |
| app.include_router(health.router, prefix="/api", tags=["health"]) | |
| app.include_router(chat.router, prefix="/api", tags=["chat"]) | |
| def read_root(): | |
| return {"message": "Todo App Backend API"} | |
| if __name__ == "__main__": | |
| import uvicorn | |
| import os | |
| port = int(os.environ.get("PORT", 8000)) # Hugging Face uses PORT environment variable | |
| uvicorn.run(app, host="0.0.0.0", port=port) |