init
Browse files- app.py +57 -0
- requirements.txt +2 -0
app.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 2 |
+
from fastapi.responses import Response
|
| 3 |
+
import httpx
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
PROXY_KEY = os.environ.get("PROXY_KEY")
|
| 9 |
+
|
| 10 |
+
@app.post("/proxy")
|
| 11 |
+
async def generic_proxy(request: Request):
|
| 12 |
+
# simple protection (REQUIRED on HF)
|
| 13 |
+
if PROXY_KEY:
|
| 14 |
+
if request.headers.get("x-proxy-key") != PROXY_KEY:
|
| 15 |
+
raise HTTPException(status_code=403, detail="Forbidden")
|
| 16 |
+
|
| 17 |
+
payload = await request.json()
|
| 18 |
+
|
| 19 |
+
url = payload.get("url")
|
| 20 |
+
if not url or not url.startswith(("http://", "https://")):
|
| 21 |
+
raise HTTPException(400, "Invalid url")
|
| 22 |
+
|
| 23 |
+
method = payload.get("method", "GET").upper()
|
| 24 |
+
headers = payload.get("headers", {})
|
| 25 |
+
params = payload.get("params")
|
| 26 |
+
body = payload.get("body")
|
| 27 |
+
|
| 28 |
+
async with httpx.AsyncClient(
|
| 29 |
+
follow_redirects=True,
|
| 30 |
+
timeout=60
|
| 31 |
+
) as client:
|
| 32 |
+
resp = await client.request(
|
| 33 |
+
method=method,
|
| 34 |
+
url=url,
|
| 35 |
+
headers=headers,
|
| 36 |
+
params=params,
|
| 37 |
+
content=body if isinstance(body, (str, bytes)) else None,
|
| 38 |
+
json=body if isinstance(body, (dict, list)) else None,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
return Response(
|
| 42 |
+
content=resp.content,
|
| 43 |
+
status_code=resp.status_code,
|
| 44 |
+
headers={
|
| 45 |
+
k: v for k, v in resp.headers.items()
|
| 46 |
+
if k.lower() not in ["content-encoding", "transfer-encoding"]
|
| 47 |
+
},
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
import uvicorn
|
| 52 |
+
uvicorn.run(
|
| 53 |
+
"app:app",
|
| 54 |
+
host="0.0.0.0",
|
| 55 |
+
port=7860,
|
| 56 |
+
reload=False
|
| 57 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
uvicorn
|
| 2 |
+
fastapi
|