Update app.py
Browse files
app.py
CHANGED
|
@@ -26,9 +26,23 @@ async def get_http_client():
|
|
| 26 |
http2=True
|
| 27 |
)
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"])
|
| 30 |
-
async def
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
try:
|
|
|
|
| 32 |
url = f"{TARGET_URL}/{path}"
|
| 33 |
|
| 34 |
# 获取并处理请求头
|
|
@@ -55,14 +69,13 @@ async def proxy(path: str, request: Request):
|
|
| 55 |
response_headers = dict(response.headers)
|
| 56 |
response_headers.pop('transfer-encoding', None)
|
| 57 |
response_headers.pop('content-encoding', None)
|
| 58 |
-
response_headers.pop('content-length', None)
|
| 59 |
|
| 60 |
# 修改涉及原始域名的响应头
|
| 61 |
for key, value in response_headers.items():
|
| 62 |
if isinstance(value, str) and TARGET_URL in value:
|
| 63 |
response_headers[key] = value.replace(TARGET_URL, str(request.base_url).rstrip('/'))
|
| 64 |
|
| 65 |
-
# 使用 Response 而不是 StreamingResponse
|
| 66 |
return Response(
|
| 67 |
content=response.content,
|
| 68 |
status_code=response.status_code,
|
|
|
|
| 26 |
http2=True
|
| 27 |
)
|
| 28 |
|
| 29 |
+
# 处理 /api 和 /api/v1 的特殊路由
|
| 30 |
+
@app.api_route("/api{rest:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"])
|
| 31 |
+
async def api_proxy(rest: str, request: Request):
|
| 32 |
+
# 移除开头的斜杠,因为 TARGET_URL 已经包含了斜杠
|
| 33 |
+
if rest.startswith('/'):
|
| 34 |
+
rest = rest[1:]
|
| 35 |
+
return await proxy_handler(rest, request)
|
| 36 |
+
|
| 37 |
+
# 处理其他所有路径的通用路由
|
| 38 |
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"])
|
| 39 |
+
async def general_proxy(path: str, request: Request):
|
| 40 |
+
return await proxy_handler(path, request)
|
| 41 |
+
|
| 42 |
+
# 代理处理函数
|
| 43 |
+
async def proxy_handler(path: str, request: Request):
|
| 44 |
try:
|
| 45 |
+
# 构建目标URL
|
| 46 |
url = f"{TARGET_URL}/{path}"
|
| 47 |
|
| 48 |
# 获取并处理请求头
|
|
|
|
| 69 |
response_headers = dict(response.headers)
|
| 70 |
response_headers.pop('transfer-encoding', None)
|
| 71 |
response_headers.pop('content-encoding', None)
|
| 72 |
+
response_headers.pop('content-length', None)
|
| 73 |
|
| 74 |
# 修改涉及原始域名的响应头
|
| 75 |
for key, value in response_headers.items():
|
| 76 |
if isinstance(value, str) and TARGET_URL in value:
|
| 77 |
response_headers[key] = value.replace(TARGET_URL, str(request.base_url).rstrip('/'))
|
| 78 |
|
|
|
|
| 79 |
return Response(
|
| 80 |
content=response.content,
|
| 81 |
status_code=response.status_code,
|