File size: 2,254 Bytes
3e8f7f6
 
4d82260
 
3e8f7f6
4d82260
 
 
 
3e8f7f6
4d82260
3e8f7f6
 
4d82260
 
 
 
 
 
 
 
3e8f7f6
 
 
 
 
 
4d82260
 
3e8f7f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d82260
 
 
3e8f7f6
4d82260
fb8624f
 
 
 
 
 
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
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")