Spaces:
Running
Running
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# main.py
|
| 2 |
+
from fastapi import FastAPI, Request, UploadFile
|
| 3 |
+
from typing import Any, Dict
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
@app.get("/")
|
| 9 |
+
def root():
|
| 10 |
+
return {"ok": True, "msg": "Send POST to /echo"}
|
| 11 |
+
|
| 12 |
+
@app.get("/ping")
|
| 13 |
+
def ping():
|
| 14 |
+
return {"pong": True}
|
| 15 |
+
|
| 16 |
+
@app.post("/echo")
|
| 17 |
+
async def echo(request: Request) -> Dict[str, Any]:
|
| 18 |
+
# اطبع تفاصيل الريكويست في الكونسول
|
| 19 |
+
body_bytes = await request.body()
|
| 20 |
+
print("\n" + "="*30 + " NEW REQUEST " + "="*30)
|
| 21 |
+
print("Method:", request.method)
|
| 22 |
+
print("URL:", str(request.url))
|
| 23 |
+
print("Headers:", dict(request.headers))
|
| 24 |
+
print("Raw body (bytes):", body_bytes)
|
| 25 |
+
print("Raw body (str):", body_bytes.decode("utf-8", errors="ignore"))
|
| 26 |
+
|
| 27 |
+
# جرّب تفك JSON، ولو فشل جرّب Form، وإلا رجّع النص الخام
|
| 28 |
+
try:
|
| 29 |
+
parsed = await request.json()
|
| 30 |
+
except Exception:
|
| 31 |
+
try:
|
| 32 |
+
form = await request.form()
|
| 33 |
+
parsed = {}
|
| 34 |
+
for k, v in form.items():
|
| 35 |
+
# لو فيه ملفات
|
| 36 |
+
if isinstance(v, UploadFile):
|
| 37 |
+
parsed[k] = {"filename": v.filename, "content_type": v.content_type}
|
| 38 |
+
else:
|
| 39 |
+
parsed[k] = v
|
| 40 |
+
except Exception:
|
| 41 |
+
parsed = body_bytes.decode("utf-8", errors="ignore")
|
| 42 |
+
|
| 43 |
+
return {
|
| 44 |
+
"received": parsed,
|
| 45 |
+
"info": {
|
| 46 |
+
"method": request.method,
|
| 47 |
+
"url": str(request.url),
|
| 48 |
+
"headers": dict(request.headers),
|
| 49 |
+
},
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
# للتشغيل مباشرةً: uvicorn main:app --reload --host 0.0.0.0 --port 8000
|