测试代理是否可访问目标站点(默认 https://labs.google/)
(
request: ProxyTestRequest,
token: str = Depends(verify_admin_token)
)
| 1293 | |
| 1294 | @router.post("/api/proxy/test") |
| 1295 | async def test_proxy_connectivity( |
| 1296 | request: ProxyTestRequest, |
| 1297 | token: str = Depends(verify_admin_token) |
| 1298 | ): |
| 1299 | """测试代理是否可访问目标站点(默认 https://labs.google/)""" |
| 1300 | proxy_input = (request.proxy_url or "").strip() |
| 1301 | test_url = (request.test_url or "https://labs.google/").strip() |
| 1302 | timeout_seconds = int(request.timeout_seconds or 15) |
| 1303 | timeout_seconds = max(5, min(timeout_seconds, 60)) |
| 1304 | |
| 1305 | if not proxy_input: |
| 1306 | return { |
| 1307 | "success": False, |
| 1308 | "message": "代理地址为空", |
| 1309 | "test_url": test_url |
| 1310 | } |
| 1311 | |
| 1312 | try: |
| 1313 | proxy_url = proxy_manager.normalize_proxy_url(proxy_input) |
| 1314 | except ValueError as e: |
| 1315 | return { |
| 1316 | "success": False, |
| 1317 | "message": str(e), |
| 1318 | "test_url": test_url |
| 1319 | } |
| 1320 | |
| 1321 | start_time = time.time() |
| 1322 | try: |
| 1323 | proxies = {"http": proxy_url, "https": proxy_url} |
| 1324 | async with AsyncSession() as session: |
| 1325 | resp = await session.get( |
| 1326 | test_url, |
| 1327 | proxies=proxies, |
| 1328 | timeout=timeout_seconds, |
| 1329 | impersonate="chrome120", |
| 1330 | allow_redirects=True, |
| 1331 | verify=False |
| 1332 | ) |
| 1333 | |
| 1334 | elapsed_ms = int((time.time() - start_time) * 1000) |
| 1335 | status_code = resp.status_code |
| 1336 | final_url = str(resp.url) |
| 1337 | ok = 200 <= status_code < 400 |
| 1338 | |
| 1339 | return { |
| 1340 | "success": ok, |
| 1341 | "message": "代理可用" if ok else f"代理可连通,但目标返回状态码 {status_code}", |
| 1342 | "test_url": test_url, |
| 1343 | "final_url": final_url, |
| 1344 | "status_code": status_code, |
| 1345 | "elapsed_ms": elapsed_ms |
| 1346 | } |
| 1347 | except Exception as e: |
| 1348 | elapsed_ms = int((time.time() - start_time) * 1000) |
| 1349 | return { |
| 1350 | "success": False, |
| 1351 | "message": f"代理测试失败: {str(e)}", |
| 1352 | "test_url": test_url, |
nothing calls this directly
no test coverage detected