Is that possible to replace hyperlinks in StreamingResponse?
I'm using below code to stream HTML content.
from starlette.requests import Request
from starlette.responses import StreamingResponse
from starlette.background import BackgroundTask
import httpx
client = httpx.AsyncClient(base_url="http://containername:7800/")
async def _reverse_proxy(request: Request):
url = httpx.URL(path=request.url.path, query=request.url.query.encode("utf-8"))
rp_req = client.build_request(
request.method, url, headers=request.headers.raw, content=await request.body()
)
rp_resp = await client.send(rp_req, stream=True)
return StreamingResponse(
rp_resp.aiter_raw(),
status_code=rp_resp.status_code,
headers=rp_resp.headers,
background=BackgroundTask(rp_resp.aclose),
)
app.add_route("/titles/{path:path}", _reverse_proxy, ["GET", "POST"])
It's working fine, but I would like to replace a href links.
Is that possible?
I've tired to wrap the generator like below:
async def adjust_response(iterable):
# Adjust hyperlinks in response.
async for element in iterable.aiter_raw():
yield element.decode("utf-8").replace("/admin", "/gateway/admins/SERVICE_A").encode("utf-8")
but this caused that error:
h11._util.LocalProtocolError: Too much data for declared Content-Length