tuhbooh commited on
Commit
bccdc0c
·
verified ·
1 Parent(s): 8b4dc08

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -29
app.py CHANGED
@@ -1,61 +1,60 @@
1
  from fastapi import FastAPI, Request, HTTPException
2
  import time
3
  import uvicorn
4
- import httpx
 
5
 
6
  app = FastAPI()
7
 
8
- # Lưu trữ thời gian request cuối cùng của mỗi IP
9
- # { "1.2.3.4": 1712345678.9 }
10
  last_request_time = {}
11
 
12
- async def get_real_location(ip: str):
13
- """Gọi API bên thứ 3 để lấy thông tin vị trí thật từ IP"""
14
  if ip == "unknown" or ip.startswith("127."):
15
- return "Local/Unknown"
16
-
17
  try:
18
- async with httpx.AsyncClient() as client:
19
- # Sử dụng ip-api.com (miễn phí cho thử nghiệm)
20
- response = await client.get(f"http://ip-api.com/json/{ip}")
21
- data = response.json()
22
  if data.get("status") == "success":
23
  return f"{data.get('city')}, {data.get('country')}"
24
- except Exception:
25
  pass
26
- return "Unknown"
27
 
28
  @app.get("/")
29
  async def root(request: Request):
30
- # 1. Lấy Client IP chuẩn
31
  headers = request.headers
32
- forwarded = headers.get("x-forwarded-for")
33
- client_ip = forwarded.split(",")[0] if forwarded else "unknown"
34
-
35
- # 2. Rate Limiting: 1 request / 0.5s
36
- current_time = time.time()
37
- last_time = last_request_time.get(client_ip, 0)
38
 
39
- if current_time - last_time < 0.5:
40
- raise HTTPException(status_code=429, detail="Too Many Requests - Wait 0.5s")
41
-
42
- last_request_time[client_ip] = current_time
 
43
 
44
- # 3. Lấy vị trí thật (City, Country)
45
- real_loc = await get_real_location(client_ip)
 
 
 
46
 
 
 
 
 
 
47
  return {
48
  "fl": "998f87",
49
  "h": headers.get("host", "huggingface.co"),
50
  "ip": client_ip,
51
- "ts": current_time,
52
  "visit_scheme": "https",
53
  "uag": headers.get("user-agent", "unknown"),
54
- "loc": real_loc, # Vị trí thật từ API
55
  "tls": "TLSv1.3",
56
  "status": "active"
57
  }
58
 
59
  if __name__ == "__main__":
60
- # Giữ nguyên cấu hình cho Hugging Face Spaces
61
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
  from fastapi import FastAPI, Request, HTTPException
2
  import time
3
  import uvicorn
4
+ import json
5
+ from urllib.request import urlopen
6
 
7
  app = FastAPI()
8
 
 
 
9
  last_request_time = {}
10
 
11
+ def get_real_location_sync(ip: str):
12
+ """Lấy vị trí bằng thư viện chuẩn urllib (không cần cài thêm gì)"""
13
  if ip == "unknown" or ip.startswith("127."):
14
+ return "VN"
 
15
  try:
16
+ # Gọi API lấy vị trí (timeout 2s để không làm chậm app)
17
+ with urlopen(f"http://ip-api.com/json/{ip}", timeout=2) as response:
18
+ data = json.loads(response.read().decode())
 
19
  if data.get("status") == "success":
20
  return f"{data.get('city')}, {data.get('country')}"
21
+ except:
22
  pass
23
+ return "VN"
24
 
25
  @app.get("/")
26
  async def root(request: Request):
 
27
  headers = request.headers
28
+ client_ip = headers.get("x-forwarded-for", "unknown").split(",")[0]
 
 
 
 
 
29
 
30
+ # --- Rate Limiting (0.5s) ---
31
+ now = time.time()
32
+ if client_ip in last_request_time and (now - last_request_time[client_ip] < 0.5):
33
+ raise HTTPException(status_code=429, detail="Slow down!")
34
+ last_request_time[client_ip] = now
35
 
36
+ # --- Lấy vị trí thật ---
37
+ # Nếu chạy trên Hugging Face, nó có sẵn header 'cf-ipcity' và 'cf-ipcountry'
38
+ # Bạn có thể ưu tiên lấy từ header cho nhanh, nếu không có mới gọi API
39
+ city = headers.get("cf-ipcity", "")
40
+ country = headers.get("cf-ipcountry", "VN")
41
 
42
+ if city:
43
+ real_loc = f"{city}, {country}"
44
+ else:
45
+ real_loc = get_real_location_sync(client_ip)
46
+
47
  return {
48
  "fl": "998f87",
49
  "h": headers.get("host", "huggingface.co"),
50
  "ip": client_ip,
51
+ "ts": now,
52
  "visit_scheme": "https",
53
  "uag": headers.get("user-agent", "unknown"),
54
+ "loc": real_loc,
55
  "tls": "TLSv1.3",
56
  "status": "active"
57
  }
58
 
59
  if __name__ == "__main__":
 
60
  uvicorn.run(app, host="0.0.0.0", port=7860)