Skip to content

Instantly share code, notes, and snippets.

@chrisvdg
Created April 18, 2024 11:27
Show Gist options
  • Save chrisvdg/d3f3645260fae2a952124f6db42e755b to your computer and use it in GitHub Desktop.
Save chrisvdg/d3f3645260fae2a952124f6db42e755b to your computer and use it in GitHub Desktop.
Quick and dirty proxy server to log passing traffic
from fastapi import FastAPI, Request, Response
import secrets
import requests
from datetime import datetime
targetBaseUrl = "http://localhost:5000"
app = FastAPI()
@app.api_route("/{rest_of_path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def proxyPrint(request: Request, rest_of_path: str) -> Response:
requestId = secrets.token_urlsafe(5)
print(rest_of_path)
body = await request.body()
print(
f"{datetime.now().isoformat()} [{requestId}] Incoming request {request.method}: {request.url.path}\n{body.decode()}"
)
proxyResp: requests.Response = requests.request(
method=request.method,
data=body,
url=f"{targetBaseUrl}/{request.url.path}",
params=request.path_params,
headers=request.headers,
)
print(
f"{datetime.now().isoformat()} [{requestId}] Proxy response: {proxyResp.status_code}\n{proxyResp.text}"
)
return Response(
content=proxyResp.text,
status_code=proxyResp.status_code,
headers=proxyResp.headers,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment