|
@@ -0,0 +1,68 @@
|
|
|
+#!/usr/bin/env python3
|
|
|
+# -*- coding: utf-8 -*-
|
|
|
+from fastapi import APIRouter, Request, HTTPException, Response
|
|
|
+import requests
|
|
|
+import asyncio
|
|
|
+import json
|
|
|
+from extensions import logger
|
|
|
+
|
|
|
+TARGET_BASE_URL = "http://172.26.1.85:8530/api"
|
|
|
+
|
|
|
+router = APIRouter()
|
|
|
+
|
|
|
+def sync_fetch(method, url, params=None, headers=None, data=None):
|
|
|
+ try:
|
|
|
+ response = requests.request(
|
|
|
+ method,
|
|
|
+ url,
|
|
|
+ params=params,
|
|
|
+ headers=headers,
|
|
|
+ data=data,
|
|
|
+ timeout=30 # 设置超时
|
|
|
+ )
|
|
|
+ return Response(
|
|
|
+ content=response.content,
|
|
|
+ status_code=response.status_code,
|
|
|
+ headers=dict(response.headers)
|
|
|
+ )
|
|
|
+ except Exception as e:
|
|
|
+ raise Exception(f"Requests error: {str(e)}")
|
|
|
+
|
|
|
+@router.api_route("/skwhp/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
|
|
|
+async def proxy(request: Request, path: str):
|
|
|
+ target_url = f"{TARGET_BASE_URL}/{path}"
|
|
|
+ method = request.method.lower()
|
|
|
+
|
|
|
+ params = dict(request.query_params)
|
|
|
+ headers = dict(request.headers) # 可按需筛选 headers
|
|
|
+ body = None
|
|
|
+
|
|
|
+ if method in ["post", "put", "patch"]:
|
|
|
+ try:
|
|
|
+ body = await request.body()
|
|
|
+ except:
|
|
|
+ body = None
|
|
|
+
|
|
|
+ try:
|
|
|
+ logger.info(target_url)
|
|
|
+ if body is not None:
|
|
|
+ data = body.decode(encoding='utf-8')
|
|
|
+ if len(data) > 0:
|
|
|
+ data = json.loads(data)
|
|
|
+ logger.info(data)
|
|
|
+ except:
|
|
|
+ pass
|
|
|
+
|
|
|
+ # 使用 asyncio.to_thread 在后台线程中运行同步的 requests 调用
|
|
|
+ try:
|
|
|
+ response = await asyncio.to_thread(
|
|
|
+ sync_fetch,
|
|
|
+ method,
|
|
|
+ target_url,
|
|
|
+ params=params,
|
|
|
+ headers=headers,
|
|
|
+ data=body
|
|
|
+ )
|
|
|
+ return response
|
|
|
+ except Exception as e:
|
|
|
+ raise HTTPException(status_code=500, detail=f"代理请求失败: {str(e)}")
|