api-proxy / app.py
tanbushi's picture
Update app.py
db5a981 verified
raw
history blame
1.81 kB
# uvicorn app:app --host 0.0.0.0 --port 7860 --reload
from fastapi import FastAPI, Request, HTTPException
import re
import httpx
app = FastAPI()
@app.get("/")
def greet_json():
return {"Hello": "World!"}
@app.get("/v1/{dest_url:path}")
async def gre_dest_url(dest_url: str):
return dest_url
@app.post("/v1/{dest_url:path}")
async def proxy_url(dest_url: str, request: Request):
body = await request.body()
headers = dict(request.headers) # 将请求头转换为字典
# 移除 Content-Length 和 Host 头部
if 'content-length' in headers:
del headers['content-length']
if 'host' in headers:
del headers['host']
headers['User-Agent']='PostmanRuntime/7.43.0'
dest_url = re.sub('/', '://', dest_url, count=1)
async with httpx.AsyncClient() as client:
try:
# 向目标 URL 发送 POST 请求
response = await client.post(dest_url, content=body, headers=headers)
# 检查响应状态码
if response.status_code == 200:
# 检查响应内容类型是否为 JSON
if 'application/json' in response.headers.get('content-type', ''):
return response.json()
else:
return {"error": "Response is not in JSON format"}
else:
# 将错误响应转换为 JSON 格式并返回给客户端
try:
error_data = response.json()
except ValueError:
error_data = {"status_code": response.status_code, "detail": response.text}
return error_data
except httpx.RequestError as e:
# 处理请求错误
raise HTTPException(status_code=500, detail=str(e))