Spaces:
Sleeping
Sleeping
update
Browse files- proxyserver-fastapi.py +44 -44
proxyserver-fastapi.py
CHANGED
|
@@ -114,52 +114,52 @@ async def proxy_request(url_path: str, request: Request):
|
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
-
#
|
| 118 |
-
|
| 119 |
|
| 120 |
-
#
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
|
| 164 |
# if __name__ == '__main__':
|
| 165 |
# # 提示:请确保您已激活 conda 环境 'any-api' (conda activate any-api)
|
|
|
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
+
# 获取请求体
|
| 118 |
+
request_body = await request.body()
|
| 119 |
|
| 120 |
+
# 获取查询参数
|
| 121 |
+
query_params = request.query_params
|
| 122 |
+
|
| 123 |
+
async with httpx.AsyncClient(verify=True, follow_redirects=False) as client:
|
| 124 |
+
try:
|
| 125 |
+
# 使用 httpx 库向目标 URL 发送请求
|
| 126 |
+
resp = await client.request(
|
| 127 |
+
method=request.method,
|
| 128 |
+
url=target_url,
|
| 129 |
+
headers=headers,
|
| 130 |
+
content=request_body, # 使用 content 传递请求体
|
| 131 |
+
params=query_params,
|
| 132 |
+
timeout=30.0, # 设置超时时间为30秒
|
| 133 |
+
)
|
| 134 |
+
print('headers',headers)
|
| 135 |
+
|
| 136 |
+
# 打印目标 API 返回的实际状态码和响应体,用于调试
|
| 137 |
+
print(f"目标API响应状态码: {resp.status_code}")
|
| 138 |
+
print(f"目标API响应体: {resp.text[:500]}...") # 打印前500个字符,避免过长
|
| 139 |
+
|
| 140 |
+
# 构建响应头部
|
| 141 |
+
excluded_headers = ['content-encoding'] # 保持与 Flask 版本一致
|
| 142 |
+
response_headers = {
|
| 143 |
+
name: value for name, value in resp.headers.items()
|
| 144 |
+
if name.lower() not in excluded_headers
|
| 145 |
+
}
|
| 146 |
|
| 147 |
+
# 返回流式响应内容
|
| 148 |
+
# httpx 的 .aiter_bytes() 返回异步迭代器
|
| 149 |
+
async def generate_response():
|
| 150 |
+
async for chunk in resp.aiter_bytes(chunk_size=8192):
|
| 151 |
+
yield chunk
|
| 152 |
+
|
| 153 |
+
return StreamingResponse(generate_response(), status_code=resp.status_code, headers=response_headers)
|
| 154 |
+
|
| 155 |
+
except httpx.RequestError as e:
|
| 156 |
+
error_detail = f"代理请求到 {target_url} 失败: {type(e).__name__} - {e}"
|
| 157 |
+
print(f"代理请求失败: {error_detail}")
|
| 158 |
+
if e.request:
|
| 159 |
+
print(f"请求信息: {e.request.method} {e.request.url}")
|
| 160 |
+
if hasattr(e, 'response') and e.response:
|
| 161 |
+
print(f"响应信息: {e.response.status_code} {e.response.text[:200]}...")
|
| 162 |
+
raise HTTPException(status_code=500, detail=error_detail)
|
| 163 |
|
| 164 |
# if __name__ == '__main__':
|
| 165 |
# # 提示:请确保您已激活 conda 环境 'any-api' (conda activate any-api)
|