Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,59 +1,66 @@
|
|
1 |
-
from fastapi import FastAPI, Request, HTTPException
|
|
|
2 |
import httpx
|
3 |
-
from starlette.responses import RedirectResponse
|
4 |
|
5 |
app = FastAPI()
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
@app.get("/forward/")
|
8 |
async def forward(request: Request):
|
9 |
-
# Extract query parameters as a dictionary
|
10 |
query_params = dict(request.query_params)
|
11 |
-
|
12 |
-
# If no parameters are submitted, show help information
|
13 |
-
if not query_params:
|
14 |
-
return {
|
15 |
-
"error": "No parameters provided.",
|
16 |
-
"help": "This endpoint forwards parameters to a specified URL. "
|
17 |
-
"Use `param1` to specify the URL to forward to, followed by any other parameters you wish to forward."
|
18 |
-
}
|
19 |
-
|
20 |
-
# Extract the URL to forward to (param1)
|
21 |
forward_url = query_params.pop('param1', None)
|
22 |
|
23 |
-
# Check if the forward URL is present
|
24 |
if not forward_url:
|
25 |
-
|
|
|
|
|
|
|
26 |
|
27 |
-
# Validate the forward URL (basic validation)
|
28 |
if not (forward_url.startswith('http://') or forward_url.startswith('https://')):
|
29 |
-
|
|
|
|
|
|
|
30 |
|
31 |
-
|
32 |
-
if query_params: # If there are other parameters to forward
|
33 |
params_as_str = "&".join([f"{key}={value}" for key, value in query_params.items()])
|
34 |
forward_url_with_params = f"{forward_url}?{params_as_str}"
|
35 |
else:
|
36 |
forward_url_with_params = forward_url
|
37 |
|
38 |
try:
|
39 |
-
# Forward the request to the new URL using httpx for asynchronous HTTP requests
|
40 |
async with httpx.AsyncClient() as client:
|
41 |
response = await client.get(forward_url_with_params)
|
42 |
-
response.raise_for_status()
|
43 |
-
|
44 |
except httpx.RequestError as e:
|
45 |
-
|
46 |
-
raise HTTPException(status_code=500, detail=f"Request error: {str(e)}")
|
47 |
except httpx.HTTPStatusError as e:
|
48 |
-
|
49 |
-
raise HTTPException(status_code=e.response.status_code, detail=f"Error response from forwarded URL: {str(e)}")
|
50 |
|
51 |
try:
|
52 |
-
# Attempt to return the JSON response
|
53 |
return response.json()
|
54 |
except ValueError:
|
55 |
-
|
56 |
-
return Response(content=response.text, media_type="text/plain")
|
57 |
|
58 |
# To run the server:
|
59 |
# uvicorn app:app --reload
|
|
|
1 |
+
from fastapi import FastAPI, Request, HTTPException
|
2 |
+
from fastapi.responses import JSONResponse, HTMLResponse
|
3 |
import httpx
|
|
|
4 |
|
5 |
app = FastAPI()
|
6 |
|
7 |
+
@app.get("/")
|
8 |
+
async def root():
|
9 |
+
# Return a help message or documentation as HTML
|
10 |
+
help_html = """
|
11 |
+
<html>
|
12 |
+
<head>
|
13 |
+
<title>Hugging Face App Help</title>
|
14 |
+
</head>
|
15 |
+
<body>
|
16 |
+
<h2>Welcome to the Hugging Face Forwarder App</h2>
|
17 |
+
<p>To use this app, make a GET request to <code>/forward/?param1=YOUR_URL&otherParams=...</code></p>
|
18 |
+
<ul>
|
19 |
+
<li><code>param1</code> is the URL to which the other parameters will be forwarded.</li>
|
20 |
+
<li>Include any other parameters you wish to forward in the query string.</li>
|
21 |
+
</ul>
|
22 |
+
<p>For example: <code>/forward/?param1=https://example.com&data=someData</code></p>
|
23 |
+
</body>
|
24 |
+
</html>
|
25 |
+
"""
|
26 |
+
return HTMLResponse(content=help_html)
|
27 |
+
|
28 |
@app.get("/forward/")
|
29 |
async def forward(request: Request):
|
|
|
30 |
query_params = dict(request.query_params)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
forward_url = query_params.pop('param1', None)
|
32 |
|
|
|
33 |
if not forward_url:
|
34 |
+
return JSONResponse(
|
35 |
+
status_code=400,
|
36 |
+
content={"error": "param1 (forward URL) is required. Visit the main page for usage instructions."}
|
37 |
+
)
|
38 |
|
|
|
39 |
if not (forward_url.startswith('http://') or forward_url.startswith('https://')):
|
40 |
+
return JSONResponse(
|
41 |
+
status_code=400,
|
42 |
+
content={"error": "Invalid URL. URL must start with http:// or https://"}
|
43 |
+
)
|
44 |
|
45 |
+
if query_params:
|
|
|
46 |
params_as_str = "&".join([f"{key}={value}" for key, value in query_params.items()])
|
47 |
forward_url_with_params = f"{forward_url}?{params_as_str}"
|
48 |
else:
|
49 |
forward_url_with_params = forward_url
|
50 |
|
51 |
try:
|
|
|
52 |
async with httpx.AsyncClient() as client:
|
53 |
response = await client.get(forward_url_with_params)
|
54 |
+
response.raise_for_status()
|
|
|
55 |
except httpx.RequestError as e:
|
56 |
+
return JSONResponse(status_code=500, content={"error": f"Request error: {str(e)}"})
|
|
|
57 |
except httpx.HTTPStatusError as e:
|
58 |
+
return JSONResponse(status_code=e.response.status_code, content={"error": f"Error response from forwarded URL: {str(e)}"})
|
|
|
59 |
|
60 |
try:
|
|
|
61 |
return response.json()
|
62 |
except ValueError:
|
63 |
+
return HTMLResponse(content=response.text, media_type="text/plain")
|
|
|
64 |
|
65 |
# To run the server:
|
66 |
# uvicorn app:app --reload
|