from fastapi import FastAPI, Request, HTTPException from fastapi.responses import JSONResponse import logging import sys import uvicorn # Import uvicorn # Configure logging to output to stdout logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') app = FastAPI() @app.post("/") async def handle_request(request: Request): """Handles incoming POST requests, logs details, and returns a response.""" logging.info("="*20 + " New Request Received " + "="*20) # Log headers logging.info("Headers:") for header, value in request.headers.items(): logging.info(f" {header}: {value}") # Log body content_type = request.headers.get('content-type') logging.info("Body:") try: if content_type and 'application/json' in content_type: json_data = await request.json() logging.info("JSON Body:") logging.info(json_data) else: body_data = await request.body() logging.info("Raw Body:") # Try decoding as text, fallback to raw bytes if fails try: logging.info(body_data.decode('utf-8')) except UnicodeDecodeError: logging.info(f"Raw Body (non-UTF-8): {body_data}") except Exception as e: logging.error(f"Error processing body: {e}") # Log raw body on error as well try: body_data = await request.body() logging.info(f"Raw Body (on error): {body_data}") except Exception as read_err: logging.error(f"Could not even read raw body on error: {read_err}") raise HTTPException(status_code=400, detail=f"Error processing request body: {e}") logging.info("="*20 + " End of Request " + "="*20 + "\n") return JSONResponse(content={"status": "success", "message": "Request received and logged."}, status_code=200) # This block allows direct execution of the app for local debugging # and ensures compatibility with Hugging Face Spaces if __name__ == "__main__": # Hugging Face Spaces expects the app on port 7860 # Using 0.0.0.0 to be accessible externally uvicorn.run("app:app", host="0.0.0.0", port=7860, log_level="info")