airsltd commited on
Commit
5bf06f3
·
1 Parent(s): 6fdfa8b
Files changed (1) hide show
  1. proxyserver-fastapi.py +46 -44
proxyserver-fastapi.py CHANGED
@@ -97,6 +97,8 @@ async def proxy_request(url_path: str, request: Request):
97
  headers["authorization"]=f"Bearer {third_party_api_key}"
98
  headers["content-type"]="application/json"
99
  headers["user-agent"]="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
 
 
100
  print("\n\n请求头部-2: ")
101
  pretty_json = json.dumps(headers, indent=4, sort_keys=True, ensure_ascii=False)
102
  print(pretty_json)
@@ -104,52 +106,52 @@ async def proxy_request(url_path: str, request: Request):
104
 
105
 
106
 
107
- # 获取请求体
108
- request_body = await request.body()
109
 
110
- # 获取查询参数
111
- query_params = request.query_params
112
-
113
- async with httpx.AsyncClient(verify=True, follow_redirects=False) as client:
114
- try:
115
- # 使用 httpx 库向目标 URL 发送请求
116
- resp = await client.request(
117
- method=request.method,
118
- url=target_url,
119
- headers=headers,
120
- content=request_body, # 使用 content 传递请求体
121
- params=query_params,
122
- timeout=30.0, # 设置超时时间为30秒
123
- )
124
- print('headers',headers)
125
-
126
- # 打印目标 API 返回的实际状态码和响应体,用于调试
127
- print(f"目标API响应状态码: {resp.status_code}")
128
- print(f"目标API响应体: {resp.text[:500]}...") # 打印前500个字符,避免过长
129
-
130
- # 构建响应头部
131
- excluded_headers = ['content-encoding'] # 保持与 Flask 版本一致
132
- response_headers = {
133
- name: value for name, value in resp.headers.items()
134
- if name.lower() not in excluded_headers
135
- }
136
 
137
- # 返回流式响应内容
138
- # httpx 的 .aiter_bytes() 返回异步迭代器
139
- async def generate_response():
140
- async for chunk in resp.aiter_bytes(chunk_size=8192):
141
- yield chunk
142
-
143
- return StreamingResponse(generate_response(), status_code=resp.status_code, headers=response_headers)
144
-
145
- except httpx.RequestError as e:
146
- error_detail = f"代理请求到 {target_url} 失败: {type(e).__name__} - {e}"
147
- print(f"代理请求失败: {error_detail}")
148
- if e.request:
149
- print(f"请求信息: {e.request.method} {e.request.url}")
150
- if hasattr(e, 'response') and e.response:
151
- print(f"响应信息: {e.response.status_code} {e.response.text[:200]}...")
152
- raise HTTPException(status_code=500, detail=error_detail)
153
 
154
  # if __name__ == '__main__':
155
  # # 提示:请确保您已激活 conda 环境 'any-api' (conda activate any-api)
 
97
  headers["authorization"]=f"Bearer {third_party_api_key}"
98
  headers["content-type"]="application/json"
99
  headers["user-agent"]="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
100
+
101
+
102
  print("\n\n请求头部-2: ")
103
  pretty_json = json.dumps(headers, indent=4, sort_keys=True, ensure_ascii=False)
104
  print(pretty_json)
 
106
 
107
 
108
 
109
+ # # 获取请求体
110
+ # request_body = await request.body()
111
 
112
+ # # 获取查询参数
113
+ # query_params = request.query_params
114
+
115
+ # async with httpx.AsyncClient(verify=True, follow_redirects=False) as client:
116
+ # try:
117
+ # # 使用 httpx 库向目标 URL 发送请求
118
+ # resp = await client.request(
119
+ # method=request.method,
120
+ # url=target_url,
121
+ # headers=headers,
122
+ # content=request_body, # 使用 content 传递请求体
123
+ # params=query_params,
124
+ # timeout=30.0, # 设置超时时间为30秒
125
+ # )
126
+ # print('headers',headers)
127
+
128
+ # # 打印目标 API 返回的实际状态码和响应体,用于调试
129
+ # print(f"目标API响应状态码: {resp.status_code}")
130
+ # print(f"目标API响应体: {resp.text[:500]}...") # 打印前500个字符,避免过长
131
+
132
+ # # 构建响应头部
133
+ # excluded_headers = ['content-encoding'] # 保持与 Flask 版本一致
134
+ # response_headers = {
135
+ # name: value for name, value in resp.headers.items()
136
+ # if name.lower() not in excluded_headers
137
+ # }
138
 
139
+ # # 返回流式响应内容
140
+ # # httpx 的 .aiter_bytes() 返回异步迭代器
141
+ # async def generate_response():
142
+ # async for chunk in resp.aiter_bytes(chunk_size=8192):
143
+ # yield chunk
144
+
145
+ # return StreamingResponse(generate_response(), status_code=resp.status_code, headers=response_headers)
146
+
147
+ # except httpx.RequestError as e:
148
+ # error_detail = f"代理请求到 {target_url} 失败: {type(e).__name__} - {e}"
149
+ # print(f"代理请求失败: {error_detail}")
150
+ # if e.request:
151
+ # print(f"请求信息: {e.request.method} {e.request.url}")
152
+ # if hasattr(e, 'response') and e.response:
153
+ # print(f"响应信息: {e.response.status_code} {e.response.text[:200]}...")
154
+ # raise HTTPException(status_code=500, detail=error_detail)
155
 
156
  # if __name__ == '__main__':
157
  # # 提示:请确保您已激活 conda 环境 'any-api' (conda activate any-api)