Mr-Help commited on
Commit
fbc697b
·
verified ·
1 Parent(s): 2ec7d9c

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +85 -9
main.py CHANGED
@@ -2,24 +2,88 @@
2
  from fastapi import FastAPI, Request, UploadFile
3
  from typing import Any, Dict
4
  from datetime import datetime
 
5
 
6
  app = FastAPI()
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  @app.post("/echo")
9
  async def echo(request: Request) -> Dict[str, Any]:
10
  body_bytes = await request.body()
11
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
12
 
 
13
  print("\n" + "="*30 + f" 🆕 NEW REQUEST ({now}) " + "="*30)
14
- # print("🔹 Method:", request.method)
15
- # print("🌐 URL:", str(request.url))
16
- # print("📑 Headers:", dict(request.headers))
17
- # print("\n📦 Raw body (bytes):")
18
- # print(body_bytes)
19
- print("📝 Request body:")
20
- print(body_bytes.decode("utf-8", errors="ignore"))
21
- print("="*98)
22
 
 
 
 
 
 
 
 
 
23
  try:
24
  parsed = await request.json()
25
  except Exception:
@@ -32,7 +96,17 @@ async def echo(request: Request) -> Dict[str, Any]:
32
  else:
33
  parsed[k] = v
34
  except Exception:
35
- parsed = body_bytes.decode("utf-8", errors="ignore")
 
 
 
 
 
 
 
 
 
 
36
 
37
  return {
38
  "received": parsed,
@@ -42,3 +116,5 @@ async def echo(request: Request) -> Dict[str, Any]:
42
  "headers": dict(request.headers),
43
  },
44
  }
 
 
 
2
  from fastapi import FastAPI, Request, UploadFile
3
  from typing import Any, Dict
4
  from datetime import datetime
5
+ import json
6
 
7
  app = FastAPI()
8
 
9
+ def print_human_friendly(payload: Dict[str, Any]) -> None:
10
+ """
11
+ يطبع الريكوست بشكل مقروء لليوزر + إيموجيز
12
+ """
13
+ # ترتيب العرض
14
+ order = [
15
+ ("client", "👤 Client"),
16
+ ("source", "🌐 Source"),
17
+ ("event_name", "🎯 Event Name"),
18
+ ("event_id", "🧾 Event ID"),
19
+ ("value", "💰 Value"),
20
+ ("currency", "💱 Currency"),
21
+ ("transaction_id","💳 Transaction ID"),
22
+ ("content_id", "🆔 Content ID"),
23
+ ("content_type", "📦 Content Type"),
24
+ ("fbp", "🅵 fbp"),
25
+ ("fbc", "🅵 fbc"),
26
+ ("ttclid", "🕸️ ttclid"),
27
+ ("ttp", "🍪 ttp"),
28
+ ("scid", "🟪 scid"),
29
+ ("x_email", "📧 x_email (hashed)"),
30
+ ("x_phone", "📱 x_phone (hashed)"),
31
+ ("x_fn", "🧑 First Name"),
32
+ ("x_ln", "🧑 Last Name"),
33
+ ("timestamp", "⏱️ Timestamp"),
34
+ ("client_ua", "🖥️ Client UA"),
35
+ ]
36
+
37
+ print("\n" + "-"*18 + " 👀 Human-friendly view " + "-"*18)
38
+
39
+ # أطبع الحقول الأساسية
40
+ label_pad = 20
41
+ for key, label in order:
42
+ if key in payload and payload.get(key) not in (None, ""):
43
+ value = payload.get(key)
44
+ print(f"{label:<{label_pad}}: {value}")
45
+
46
+ # أطبع العناصر (contents) بشكل منسق
47
+ contents = payload.get("contents")
48
+ if isinstance(contents, list):
49
+ print("\n🧺 Contents:")
50
+ for idx, item in enumerate(contents, start=1):
51
+ if isinstance(item, dict):
52
+ cid = item.get("content_id", "-")
53
+ name = item.get("content_name", "-")
54
+ price = item.get("price", "-")
55
+ qty = item.get("quantity", "-")
56
+ print(f" #{idx} • ID: {cid} | Name: {name} | Price: {price} | Qty: {qty}")
57
+ else:
58
+ print(f" #{idx} • {item}")
59
+ elif contents is not None:
60
+ # في حالة جات سترنج JSON أو فورمات مختلف
61
+ print("\n🧺 Contents (raw):")
62
+ try:
63
+ parsed = contents if isinstance(contents, (dict, list)) else json.loads(str(contents))
64
+ print(json.dumps(parsed, ensure_ascii=False, indent=2))
65
+ except Exception:
66
+ print(str(contents))
67
+
68
+ print("-"*60 + "\n")
69
+
70
+
71
  @app.post("/echo")
72
  async def echo(request: Request) -> Dict[str, Any]:
73
  body_bytes = await request.body()
74
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
75
 
76
+ # هيدر واضح + الوقت
77
  print("\n" + "="*30 + f" 🆕 NEW REQUEST ({now}) " + "="*30)
 
 
 
 
 
 
 
 
78
 
79
+ # طباعة البودي الخام (زي ما هي عندك)
80
+ print("\n📝 Request body:")
81
+ raw_text = body_bytes.decode("utf-8", errors="ignore")
82
+ print(raw_text)
83
+ print("="*75)
84
+
85
+ # محاولة تفكيك JSON أو فورم
86
+ parsed: Any
87
  try:
88
  parsed = await request.json()
89
  except Exception:
 
96
  else:
97
  parsed[k] = v
98
  except Exception:
99
+ # محاولة أخيرة: لو body نص بس فيه JSON
100
+ try:
101
+ parsed = json.loads(raw_text)
102
+ except Exception:
103
+ parsed = raw_text
104
+
105
+ # ✅ الطباعة الإضافية “الودية للعين” (لا تستبدل طباعة الـ JSON)
106
+ if isinstance(parsed, dict):
107
+ print_human_friendly(parsed)
108
+ else:
109
+ print("\n(ℹ️ Human-friendly view skipped: payload is not an object)\n")
110
 
111
  return {
112
  "received": parsed,
 
116
  "headers": dict(request.headers),
117
  },
118
  }
119
+
120
+ # تشغيل: uvicorn main:app --reload --host 0.0.0.0 --port 8000