bibibi12345 commited on
Commit
3e8f7f6
·
1 Parent(s): 4d82260
Files changed (3) hide show
  1. Dockerfile +1 -1
  2. app.py +38 -22
  3. requirements.txt +2 -1
Dockerfile CHANGED
@@ -24,4 +24,4 @@ ENV NAME World
24
  # Use gunicorn for a more robust production server (optional, but recommended)
25
  # CMD ["gunicorn", "--bind", "0.0.0.0:7860", "app:app"]
26
  # Fallback to Flask's built-in server for simplicity
27
- CMD ["python", "app.py"]
 
24
  # Use gunicorn for a more robust production server (optional, but recommended)
25
  # CMD ["gunicorn", "--bind", "0.0.0.0:7860", "app:app"]
26
  # Fallback to Flask's built-in server for simplicity
27
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py CHANGED
@@ -1,14 +1,16 @@
1
- from flask import Flask, request, jsonify
 
2
  import logging
3
  import sys
 
4
 
5
  # Configure logging to output to stdout
6
  logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
7
 
8
- app = Flask(__name__)
9
 
10
- @app.route('/', methods=['POST'])
11
- def handle_request():
12
  """Handles incoming POST requests, logs details, and returns a response."""
13
  logging.info("="*20 + " New Request Received " + "="*20)
14
 
@@ -17,27 +19,41 @@ def handle_request():
17
  for header, value in request.headers.items():
18
  logging.info(f" {header}: {value}")
19
 
20
- # Log JSON body if present
21
- content_type = request.headers.get('Content-Type')
22
- if content_type and 'application/json' in content_type:
23
- try:
24
- json_data = request.get_json()
 
25
  logging.info("JSON Body:")
26
  logging.info(json_data)
27
- except Exception as e:
28
- logging.error(f"Error parsing JSON: {e}")
29
- logging.info("Raw Body (JSON parsing failed):")
30
- logging.info(request.get_data(as_text=True))
31
- else:
32
- # Log raw body if not JSON
33
- logging.info("Raw Body:")
34
- logging.info(request.get_data(as_text=True))
 
 
 
 
 
 
 
 
 
 
35
 
36
  logging.info("="*20 + " End of Request " + "="*20 + "\n")
37
 
38
- return jsonify({"status": "success", "message": "Request received and logged."}), 200
39
 
40
- if __name__ == '__main__':
41
- # Hugging Face Spaces typically expect the app on port 7860
42
- # Using 0.0.0.0 to be accessible externally within the container
43
- app.run(host='0.0.0.0', port=7860)
 
 
 
 
1
+ from fastapi import FastAPI, Request, HTTPException
2
+ from fastapi.responses import JSONResponse
3
  import logging
4
  import sys
5
+ import uvicorn # Import uvicorn
6
 
7
  # Configure logging to output to stdout
8
  logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
9
 
10
+ app = FastAPI()
11
 
12
+ @app.post("/")
13
+ async def handle_request(request: Request):
14
  """Handles incoming POST requests, logs details, and returns a response."""
15
  logging.info("="*20 + " New Request Received " + "="*20)
16
 
 
19
  for header, value in request.headers.items():
20
  logging.info(f" {header}: {value}")
21
 
22
+ # Log body
23
+ content_type = request.headers.get('content-type')
24
+ logging.info("Body:")
25
+ try:
26
+ if content_type and 'application/json' in content_type:
27
+ json_data = await request.json()
28
  logging.info("JSON Body:")
29
  logging.info(json_data)
30
+ else:
31
+ body_data = await request.body()
32
+ logging.info("Raw Body:")
33
+ # Try decoding as text, fallback to raw bytes if fails
34
+ try:
35
+ logging.info(body_data.decode('utf-8'))
36
+ except UnicodeDecodeError:
37
+ logging.info(f"Raw Body (non-UTF-8): {body_data}")
38
+ except Exception as e:
39
+ logging.error(f"Error processing body: {e}")
40
+ # Log raw body on error as well
41
+ try:
42
+ body_data = await request.body()
43
+ logging.info(f"Raw Body (on error): {body_data}")
44
+ except Exception as read_err:
45
+ logging.error(f"Could not even read raw body on error: {read_err}")
46
+ raise HTTPException(status_code=400, detail=f"Error processing request body: {e}")
47
+
48
 
49
  logging.info("="*20 + " End of Request " + "="*20 + "\n")
50
 
51
+ return JSONResponse(content={"status": "success", "message": "Request received and logged."}, status_code=200)
52
 
53
+ # The following block is typically not needed when running with Uvicorn via CLI,
54
+ # but can be useful for direct execution (e.g., local debugging).
55
+ # Hugging Face Spaces will use the CMD in the Dockerfile.
56
+ # if __name__ == "__main__":
57
+ # # Default Uvicorn port is 8000, suitable for many environments.
58
+ # # Use 0.0.0.0 to be accessible externally.
59
+ # uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt CHANGED
@@ -1 +1,2 @@
1
- Flask==3.0.3
 
 
1
+ fastapi
2
+ uvicorn[standard]