Spaces:
Runtime error
Runtime error
Download backend/main.py from Amitkasar/ai-api-testing: direct link, hf CLI and curl.
- Browser
- Download file 5.77 kB
-
https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/main/backend/main.py
- Command line
-
hf download hf://spaces/Amitkasar/ai-api-testing/backend/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/main/backend/main.py
5.77 kB
| import logging | |
| import os | |
| import time | |
| from pathlib import Path | |
| # Force logging config AFTER uvicorn sets up its own β this runs at import time | |
| # which is after uvicorn's dictConfig, so it takes precedence. | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", | |
| datefmt="%H:%M:%S", | |
| force=True, # overrides any existing root-logger handlers | |
| ) | |
| import jwt as _pyjwt | |
| from cryptography.fernet import Fernet | |
| from fastapi import Depends, FastAPI, Request | |
| from fastapi.exceptions import RequestValidationError | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from slowapi import _rate_limit_exceeded_handler | |
| from slowapi.errors import RateLimitExceeded | |
| from backend import database | |
| from backend.core.auth import verify_token | |
| from backend.core.config import settings | |
| from backend.core.errors import AppError, app_error_handler | |
| from backend.core.limiter import limiter | |
| from backend.core.logging import get_logger | |
| from backend.app.api.routes import specs, assets, sessions, history, chat, execution, auth, usage | |
| import backend.app.api.routes.settings as llm_settings_router | |
| logger = get_logger(__name__) | |
| # Validate ENCRYPTION_KEY at startup β fail fast rather than silently storing plaintext | |
| if not settings.ENCRYPTION_KEY: | |
| raise RuntimeError( | |
| "ENCRYPTION_KEY must be set in .env before starting the server. " | |
| "Generate one with: python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\"" | |
| ) | |
| try: | |
| Fernet(settings.ENCRYPTION_KEY.encode()) | |
| except Exception: | |
| raise RuntimeError( | |
| "ENCRYPTION_KEY is invalid. " | |
| "Generate a valid one with: python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\"" | |
| ) | |
| # Ensure upload directories exist | |
| for category in ["audio", "video", "documents", "images", "specs"]: | |
| os.makedirs(os.path.join(settings.UPLOAD_DIR, category), exist_ok=True) | |
| app = FastAPI(title="AI API Testing Assistant") | |
| app.state.limiter = limiter | |
| async def request_logger(request: Request, call_next): | |
| start = time.perf_counter() | |
| qs = f"?{request.url.query}" if request.url.query else "" | |
| logger.info("β %s %s%s", request.method, request.url.path, qs) | |
| try: | |
| response = await call_next(request) | |
| ms = (time.perf_counter() - start) * 1000 | |
| logger.info("β %s %s%s %d (%.0fms)", request.method, request.url.path, qs, response.status_code, ms) | |
| return response | |
| except Exception as exc: | |
| ms = (time.perf_counter() - start) * 1000 | |
| logger.error("β %s %s%s ERROR (%.0fms): %s", request.method, request.url.path, qs, ms, exc) | |
| raise | |
| async def extract_user_state(request: Request, call_next): | |
| """Extract the JWT subject and store it in request.state.user so route handlers | |
| can read the current user without duplicating the verify_token dependency.""" | |
| request.state.user = None | |
| auth_header = request.headers.get("Authorization", "") | |
| if auth_header.startswith("Bearer "): | |
| try: | |
| token = auth_header[7:] | |
| payload = _pyjwt.decode(token, settings.JWT_SECRET, algorithms=["HS256"]) | |
| request.state.user = payload.get("sub") | |
| except Exception: | |
| pass | |
| return await call_next(request) | |
| app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) | |
| app.add_exception_handler(AppError, app_error_handler) | |
| async def unhandled_exception_handler(request: Request, exc: Exception): | |
| """Catch-all: log the traceback and return a CORS-safe 500 so the browser | |
| shows the real error instead of a misleading CORS-blocked message.""" | |
| logger.exception("Unhandled 500 on %s %s", request.method, request.url.path) | |
| origin = request.headers.get("origin", "") | |
| cors_headers = ( | |
| {"Access-Control-Allow-Origin": origin, "Access-Control-Allow-Credentials": "true"} | |
| if origin in settings.allowed_origins_list | |
| else {} | |
| ) | |
| return JSONResponse(status_code=500, content={"detail": str(exc)}, headers=cors_headers) | |
| # CORS β must be added after the custom HTTP middleware so it wraps all requests | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=settings.allowed_origins_list, | |
| allow_credentials=True, | |
| allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"], | |
| allow_headers=["Content-Type", "Authorization"], | |
| ) | |
| # Static file serving for uploads | |
| app.mount("/uploads", StaticFiles(directory=settings.UPLOAD_DIR), name="uploads") | |
| async def validation_exception_handler(request, exc): | |
| logger.warning("Validation error: %s", exc.errors()) | |
| return JSONResponse(status_code=422, content={"detail": exc.errors()}) | |
| _V1 = "/api/v1" | |
| # Public routes (no auth required) | |
| app.include_router(auth.router, prefix=_V1) | |
| # Protected routes β all require a valid JWT | |
| _auth = [Depends(verify_token)] | |
| app.include_router(specs.router, prefix=_V1, dependencies=_auth) | |
| app.include_router(assets.router, prefix=_V1, dependencies=_auth) | |
| app.include_router(sessions.router, prefix=_V1, dependencies=_auth) | |
| app.include_router(history.router, prefix=_V1, dependencies=_auth) | |
| app.include_router(chat.router, prefix=_V1, dependencies=_auth) | |
| app.include_router(execution.router, prefix=_V1, dependencies=_auth) | |
| app.include_router(usage.router, prefix=_V1, dependencies=_auth) | |
| app.include_router(llm_settings_router.router, prefix=_V1, dependencies=_auth) | |
| def health_check(): | |
| return {"status": "ok", "message": "AI API Testing Tool Backend running."} | |