Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 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 |
+
# Extract the URL to forward to (param1)
|
| 13 |
+
forward_url = query_params.pop('param1', None)
|
| 14 |
+
|
| 15 |
+
# Check if the forward URL is present
|
| 16 |
+
if not forward_url:
|
| 17 |
+
return {"error": "param1 (forward URL) is required"}
|
| 18 |
+
|
| 19 |
+
# Prepare the new URL with remaining query parameters
|
| 20 |
+
# This assumes that the forward URL does not already have query parameters.
|
| 21 |
+
if query_params: # If there are other parameters to forward
|
| 22 |
+
params_as_str = "&".join([f"{key}={value}" for key, value in query_params.items()])
|
| 23 |
+
forward_url_with_params = f"{forward_url}?{params_as_str}"
|
| 24 |
+
else:
|
| 25 |
+
forward_url_with_params = forward_url
|
| 26 |
+
|
| 27 |
+
# Forward the request to the new URL using httpx for asynchronous HTTP requests
|
| 28 |
+
async with httpx.AsyncClient() as client:
|
| 29 |
+
response = await client.get(forward_url_with_params)
|
| 30 |
+
|
| 31 |
+
# For simplicity, we're directly returning the response from the forwarded URL
|
| 32 |
+
# In a real application, you might want to handle different response scenarios
|
| 33 |
+
return response.json()
|
| 34 |
+
|
| 35 |
+
# To run the server:
|
| 36 |
+
# uvicorn app:app --reload
|