Browse Source

危化品代理接口

libushang 4 ngày trước cách đây
mục cha
commit
a7c055b89a
2 tập tin đã thay đổi với 70 bổ sung0 xóa
  1. 2 0
      routers/api/gateway/__init__.py
  2. 68 0
      routers/api/gateway/skwhp_api.py

+ 2 - 0
routers/api/gateway/__init__.py

@@ -22,10 +22,12 @@ import math
 import uuid
 import re
 from . import sign_api
+from . import skwhp_api
 
 router = APIRouter()
 
 router.include_router(sign_api.router)
+router.include_router(skwhp_api.router)
 
 def contains_special_characters(input_string, special_characters=";|&|$|#|'|@"):
     """

+ 68 - 0
routers/api/gateway/skwhp_api.py

@@ -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)}")