Last active
September 19, 2024 16:16
-
-
Save rakshithxaloori/894bcd133b193e19f64eeb5958655e72 to your computer and use it in GitHub Desktop.
The proxy server that routes traffic either to the test or live deployment.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import httpx | |
from fastapi import FastAPI, Request | |
from fastapi.responses import JSONResponse | |
app = FastAPI() | |
@app.middleware("http") | |
async def get_credentials(request: Request, _): | |
auth = request.headers.get("Authorization") | |
_, data = (auth or " ").split(" ", 1) | |
secret_key, _ = base64.b64decode(data).decode().split(":", 1) | |
_, mode, _ = secret_key.split("_") | |
ENDPOINT = None | |
if mode == "test": | |
ENDPOINT = TEST_ENDPOINT | |
elif mode == "live": | |
ENDPOINT = LIVE_ENDPOINT | |
async with httpx.AsyncClient() as client: | |
# Construct the new URL with the original path | |
new_url = f"{ENDPOINT.rstrip('/')}{request.url.path}" | |
# Properly encode query parameters | |
if request.url.query: | |
new_url = f"{new_url}?{request.url.query}" | |
response = await client.request( | |
method=request.method, | |
url=new_url, | |
headers=request.headers.raw, | |
content=await request.body(), | |
timeout=10, | |
) | |
# Return the response | |
return JSONResponse( | |
content=response.json(), | |
status_code=response.status_code, | |
headers=dict(response.headers), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment