1

我在基于 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)```
4

1 回答 1

0

只有httpx在流模式stream=Truehttpx.stream. 在下面的示例中,我使用路径操作收集整个响应aiter_raw并将其返回。请记住,整个响应都加载到内存中,如果您想避免这种情况,请使用 fastapiStreamingResponse

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()]))
于 2022-02-21T15:58:54.993 回答