test-p / app.py
Parssky's picture
init
21ca588
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import Response
import httpx
import os
app = FastAPI()
PROXY_KEY = os.environ.get("PROXY_KEY")
@app.post("/proxy")
async def generic_proxy(request: Request):
# simple protection (REQUIRED on HF)
if PROXY_KEY:
if request.headers.get("x-proxy-key") != PROXY_KEY:
raise HTTPException(status_code=403, detail="Forbidden")
payload = await request.json()
url = payload.get("url")
if not url or not url.startswith(("http://", "https://")):
raise HTTPException(400, "Invalid url")
method = payload.get("method", "GET").upper()
headers = payload.get("headers", {})
params = payload.get("params")
body = payload.get("body")
async with httpx.AsyncClient(
follow_redirects=True,
timeout=60
) as client:
resp = await client.request(
method=method,
url=url,
headers=headers,
params=params,
content=body if isinstance(body, (str, bytes)) else None,
json=body if isinstance(body, (dict, list)) else None,
)
return Response(
content=resp.content,
status_code=resp.status_code,
headers={
k: v for k, v in resp.headers.items()
if k.lower() not in ["content-encoding", "transfer-encoding"]
},
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app:app",
host="0.0.0.0",
port=7860,
reload=False
)