Update app/main.py
Browse files123420 unmodified lines252627282930313233345 unmodified lines4041424344456 unmodified lines525354555657585960616263646566676869from fastapi import FastAPIfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import HTMLResponse, JSONResponsefrom fastapi.middleware.cors import CORSMiddleware20 unmodified linesallow_headers=["*"],)# Import routers AFTER app is createdfrom app.routers import models, datasets, training, system, jobs# Register routers with prefixes - routers define their own prefix in APIRouter()app.include_router(models.router)app.include_router(datasets.router)app.include_router(training.router)5 unmodified linesif os.path.exists(static_dir):app.mount("/static", StaticFiles(directory=static_dir), name="static")@app.get("/", response_class=HTMLResponse)async def root():"""Serve the main dashboard"""6 unmodified lines@app.get("/health")async def health_check():"""Health check endpoint"""return {"status": "healthy", "version": "1.0.0"}@app.on_event("startup")async def startup_event():logger.info("Universal Model Trainer starting up...")# Initialize database tablesfrom app.database import init_dbawait init_db()logger.info("Database tables initialized")logger.info("Routers registered: models, datasets, training, system, jobs")@app.on_event("shutdown")async def shutdown_event():logger.info("Universal Model Trainer shutting down...")123420 unmodified lines252627282930313233343536373839404142434445465 unmodified lines52535455565758596061626364656 unmodified lines72737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150from fastapi import FastAPI, Requestfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import HTMLResponse, JSONResponsefrom fastapi.middleware.cors import CORSMiddleware20 unmodified linesallow_headers=["*"],)# Setup authentication middleware and session management# Must be done BEFORE importing routers so middleware order is correctfrom app.auth import setup_auth, AuthMiddlewarefrom app.config import settingssetup_auth(app) # Adds session middlewareapp.add_middleware(AuthMiddleware) # Protects routes based on auth config# Import routers AFTER app is created and middleware is configuredfrom app.routers import models, datasets, training, system, jobsfrom app.routers import auth as auth_router# Register auth router first (for login/logout endpoints)app.include_router(auth_router.router)# Register other routers with prefixes - routers define their own prefix in APIRouter()app.include_router(models.router)app.include_router(datasets.router)app.include_router(training.router)5 unmodified linesif os.path.exists(static_dir):app.mount("/static", StaticFiles(directory=static_dir), name="static")# Login page endpoint@app.get("/login", response_class=HTMLResponse)async def login_page():"""Serve the login page"""from app.auth import get_login_htmlreturn HTMLResponse(content=get_login_html())# Root endpoint - serves dashboard@app.get("/", response_class=HTMLResponse)async def root():"""Serve the main dashboard"""6 unmodified lines@app.get("/health")async def health_check():"""Health check endpoint - always public for monitoring"""return {"status": "healthy","version": "1.0.0","auth_enabled": bool(settings.APP_PASSWORD)}@app.on_event("startup")async def startup_event():logger.info("Universal Model Trainer starting up...")# Log authentication statusif settings.APP_PASSWORD:logger.info("Authentication enabled - password protected mode")else:logger.info("No password configured - public access mode")# Initialize database tablesfrom app.database import init_dbawait init_db()logger.info("Database tables initialized")logger.info("Routers registered: auth, models, datasets, training, system, jobs")@app.on_event("shutdown")async def shutdown_event():logger.info("Universal Model Trainer shutting down...")# Catch-all for 404 errors@app.exception_handler(404)async def not_found_handler(request: Request, exc):"""Handle 404 errors"""# Check if it's an API requestif request.url.path.startswith("/api/"):return JSONResponse(status_code=404,content={"detail": "Endpoint not found"})# Return to dashboard for HTML requestsreturn HTMLResponse(content="<script>window.location.href='/';</script>",status_code=302,headers={"location": "/"})# Exception handler for auth errorsfrom fastapi.exceptions import HTTPException@app.exception_handler(HTTPException)async def http_exception_handler(request: Request, exc: HTTPException):"""Handle HTTP exceptions with proper response type"""if exc.status_code == 401:# Unauthorized - check if it's an API or HTML requestaccept = request.headers.get("accept", "")if "text/html" in accept:from app.auth import get_login_htmlreturn HTMLResponse(content=get_login_html(error="Please log in to continue."),status_code=401)else:return JSONResponse(status_code=401,content={"detail": str(exc.detail), "login_url": "/login"})# Default error responseif request.url.path.startswith("/api/"):return JSONResponse(status_code=exc.status_code,content={"detail": str(exc.detail)})return HTMLResponse(content=f"<h1>Error {exc.status_code}</h1><p>{exc.detail}</p>",status_code=exc.status_code)
app/main.py+88-7