fastapi/uvicorn 使用 httpx.AsyncClinet 防止解压缩

fastapi/uvicorn prevent ungzipping with httpx.AsyncClinet

我从事基于 fastapi 的反向代理。我想要透明发送 AsyncClient 请求的数据。我对 gzip 页面有疑问。请你能帮我吗,如何防止在这个例子中 resp.content 的默认解压缩?

@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)```

只有在流模式 stream=Truehttpx.stream 的情况下,才有可能从 httpx 响应中提取未解码的数据。在下面的示例中,我使用 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()]))