bobocup commited on
Commit
9c30f7b
·
verified ·
1 Parent(s): 575ed5e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -1
app.py CHANGED
@@ -51,12 +51,30 @@ def init_keys():
51
  keys = []
52
  key_cycle = cycle(keys)
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  # IP白名单中间件
55
  @app.middleware("http")
56
  async def ip_whitelist(request: Request, call_next):
57
  if Config.WHITELIST_IPS and Config.WHITELIST_IPS[0]:
58
- client_ip = request.client.host
 
 
 
 
59
  if client_ip not in Config.WHITELIST_IPS:
 
60
  raise HTTPException(status_code=403, detail="IP not allowed")
61
  return await call_next(request)
62
 
@@ -133,6 +151,7 @@ async def chat_completions(request: Request):
133
  url = f"{Config.OPENAI_API_BASE}/chat/completions"
134
 
135
  print(f"Chat request to: {url}")
 
136
  print(f"Headers: {headers}")
137
  print(f"Body: {json.dumps(body_json)}")
138
 
@@ -196,6 +215,9 @@ async def proxy(path: str, request: Request):
196
  # 构建目标URL
197
  url = f"{Config.OPENAI_API_BASE}/{path}"
198
 
 
 
 
199
  async with httpx.AsyncClient() as client:
200
  try:
201
  response = await client.request(
 
51
  keys = []
52
  key_cycle = cycle(keys)
53
 
54
+ # 获取真实IP地址
55
+ def get_client_ip(request: Request) -> str:
56
+ # 尝试从各种头部获取IP
57
+ forwarded_for = request.headers.get("x-forwarded-for")
58
+ if forwarded_for:
59
+ return forwarded_for.split(",")[0].strip()
60
+
61
+ real_ip = request.headers.get("x-real-ip")
62
+ if real_ip:
63
+ return real_ip
64
+
65
+ return request.client.host
66
+
67
  # IP白名单中间件
68
  @app.middleware("http")
69
  async def ip_whitelist(request: Request, call_next):
70
  if Config.WHITELIST_IPS and Config.WHITELIST_IPS[0]:
71
+ client_ip = get_client_ip(request)
72
+ print(f"Request from IP: {client_ip}")
73
+ print(f"Allowed IPs: {Config.WHITELIST_IPS}")
74
+ print(f"Request headers: {dict(request.headers)}")
75
+
76
  if client_ip not in Config.WHITELIST_IPS:
77
+ print(f"Access denied for IP: {client_ip}")
78
  raise HTTPException(status_code=403, detail="IP not allowed")
79
  return await call_next(request)
80
 
 
151
  url = f"{Config.OPENAI_API_BASE}/chat/completions"
152
 
153
  print(f"Chat request to: {url}")
154
+ print(f"Request from IP: {get_client_ip(request)}")
155
  print(f"Headers: {headers}")
156
  print(f"Body: {json.dumps(body_json)}")
157
 
 
215
  # 构建目标URL
216
  url = f"{Config.OPENAI_API_BASE}/{path}"
217
 
218
+ print(f"Proxy request to: {url}")
219
+ print(f"Request from IP: {get_client_ip(request)}")
220
+
221
  async with httpx.AsyncClient() as client:
222
  try:
223
  response = await client.request(