2

i work on reverse proxy based on fastapi. I want transparenty send data requested by AsyncClient. I have problem with gziped pages. Please can you help me, how to prevent default ungzipping of resp.content on this example?

@app.get("/{path:path}")
async def _get ( path: str, request: Request ):
    url = await my_proxy_logic (path, request)
    async with httpx.AsyncClient() as client:
        req = client.build_request("GET", url)
        resp = await client.send(req, stream=False)
    return Response( status_code=resp.status_code, headers=resp.headers, content=resp.content)```
alex_noname
  • 26,459
  • 5
  • 69
  • 86
Jan Kortus
  • 23
  • 2
  • Please have a look at related answers [here](https://stackoverflow.com/a/74556972/17865804), as well as [here](https://stackoverflow.com/a/74239367/17865804) and [here](https://stackoverflow.com/a/73736138/17865804) – Chris Mar 10 '23 at 17:52

1 Answers1

0

It is possible to extract undecoded data from httpx response only in case of streaming mode stream=True or httpx.stream. In the example below, I collect the entire response using aiter_raw and return it from the path operation. Keep in mind that the entire response is loaded into memory, if you want to avoid this use fastapi StreamingResponse

import httpx
from fastapi import FastAPI, Request, Response

app = FastAPI()


@app.get("/pass")
async def root(request: Request):
    async with httpx.AsyncClient() as client:
        req = client.build_request('GET', 'http://httpbin.org/gzip')
        resp = await client.send(req, stream=True)
        return Response(status_code=resp.status_code, headers=resp.headers,
                        content=b"".join([part async for part in resp.aiter_raw()]))
alex_noname
  • 26,459
  • 5
  • 69
  • 86