File size: 1,550 Bytes
21ca588
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
    )