tuhbooh commited on
Commit
24d4349
·
verified ·
1 Parent(s): bccdc0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -29
app.py CHANGED
@@ -1,50 +1,33 @@
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' '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,
 
1
  from fastapi import FastAPI, Request, HTTPException
2
  import time
3
  import uvicorn
 
 
4
 
5
  app = FastAPI()
6
 
7
  last_request_time = {}
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  @app.get("/")
10
  async def root(request: Request):
11
  headers = request.headers
 
12
 
13
+ # 1. Lấy Client IP
14
+ forwarded = headers.get("x-forwarded-for")
15
+ client_ip = forwarded.split(",")[0] if forwarded else "unknown"
16
+
17
+ # 2. Rate Limiting (0.5s)
18
  now = time.time()
19
+ if client_ip in last_request_time:
20
+ if now - last_request_time[client_ip] < 0.5:
21
+ raise HTTPException(status_code=429, detail="Slow down!")
22
  last_request_time[client_ip] = now
23
 
24
+ # 3. Lấy vị trí từ Header
25
+ city = headers.get("cf-ipcity", "Unknown City")
 
 
26
  country = headers.get("cf-ipcountry", "VN")
27
+ real_loc = f"{city}, {country}"
 
 
 
 
28
 
29
  return {
30
+ "info": "This is a high-performance Network Discovery Tool designed to provide real-time connection insights and geolocation data. Made by MinhDuc with love",
31
  "fl": "998f87",
32
  "h": headers.get("host", "huggingface.co"),
33
  "ip": client_ip,