ZHIWEI666 commited on
Commit
3b1406b
·
verified ·
1 Parent(s): 9797f46

Upload router_proxy.py

Browse files
Files changed (1) hide show
  1. router_proxy.py +19 -18
router_proxy.py CHANGED
@@ -107,22 +107,24 @@ async def proxy_download(req_data: ProxyDownloadRequest, db: Session = Depends(g
107
  if hf_token and "huggingface.co" in target_url:
108
  headers["Authorization"] = f"Bearer {hf_token}"
109
 
110
- # 2. 使用 urllib 拉取真实 JSON 数据(保持原始中文文件名不自动编码)
111
  try:
112
- # 🚀 核心修复:创建 SSL 上下文,禁用证书验证(解决 Hugging Face SSL 问题)
113
- import ssl
114
- ssl_context = ssl.create_default_context()
115
- ssl_context.check_hostname = False
116
- ssl_context.verify_mode = ssl.CERT_NONE
117
-
118
- req = urllib.request.Request(target_url, headers=headers)
119
-
120
- # 🚀 使用自定义 SSL 上下文,超时 120 秒
121
- with urllib.request.urlopen(req, timeout=120, context=ssl_context) as resp:
122
- content = resp.read()
123
- # 🚀 调试日志:打印响应大小
 
 
124
  print(f"✅ 成功下载资源 [{req_data.item_id}], 大小:{len(content)} bytes")
125
- # 🚀 核心修复:使用正确的 Response 参数名,并明确指定状态码
126
  return Response(
127
  content=content,
128
  media_type="application/json",
@@ -130,10 +132,9 @@ async def proxy_download(req_data: ProxyDownloadRequest, db: Session = Depends(g
130
  headers={"Content-Disposition": f"attachment; filename={req_data.item_id}.json"}
131
  )
132
 
133
- except urllib.error.HTTPError as e:
134
- error_detail = e.read().decode('utf-8', errors='ignore') if hasattr(e, 'read') else str(e)
135
- print(f"❌ 源文件拉取失败 [HTTP {e.code}]: {error_detail}")
136
- return JSONResponse(content={"error": f"源文件拉取失败,HTTP 状态码:{e.code}"}, status_code=e.code)
137
  except Exception as e:
138
  import traceback
139
  print(f"❌ 代理下载异常:{str(e)}")
 
107
  if hf_token and "huggingface.co" in target_url:
108
  headers["Authorization"] = f"Bearer {hf_token}"
109
 
110
+ # 🚀 核心修复:使用异步 httpx 替代同步 urllib避免阻塞事件循环
111
  try:
112
+ async with httpx.AsyncClient(follow_redirects=True, verify=False, timeout=120.0) as client:
113
+ print(f"🔍 开始下载资源 [{req_data.item_id}]")
114
+ print(f"🔗 目标地址:{target_url[:80]}...")
115
+
116
+ response = await client.get(target_url, headers=headers)
117
+
118
+ if response.status_code != 200:
119
+ print(f"❌ 源文件拉取失败 [HTTP {response.status_code}]")
120
+ return JSONResponse(
121
+ content={"error": f"源文件拉取失败,HTTP 状态码:{response.status_code}"},
122
+ status_code=response.status_code
123
+ )
124
+
125
+ content = response.content
126
  print(f"✅ 成功下载资源 [{req_data.item_id}], 大小:{len(content)} bytes")
127
+
128
  return Response(
129
  content=content,
130
  media_type="application/json",
 
132
  headers={"Content-Disposition": f"attachment; filename={req_data.item_id}.json"}
133
  )
134
 
135
+ except httpx.TimeoutException as e:
136
+ print(f"❌ 下载超时:{str(e)}")
137
+ return JSONResponse(content={"error": "下载超时,请稍后重试"}, status_code=504)
 
138
  except Exception as e:
139
  import traceback
140
  print(f"❌ 代理下载异常:{str(e)}")