aiohttp 连接在 FastAPI 流响应之前关闭

问题描述 投票:0回答:1

我有一个 FastAPI 应用程序,其中包含使用 aiohttp 调用外部 API 的路由。外部 API 传输响应,我也想传输我的响应。这是我正在使用的路由器的简化版本。

from fastapi import APIRouter
from fastapi.responses import StreamingResponse
import aiohttp

router = APIRouter()

@router.post("/")
async def proxy_stream():
    async with aiohttp.ClientSession() as http_session:
        async with http_session.post(
            "https://streaming-api",
            json={"json": "body"}
        ) as response:
            
            async def process_response():
                async for chunk in response.content.iter_chunked(128):
                    # Work on chunk and then stream it
                    yield process_chunk(chunk)

            return StreamingResponse(
                process_response()
            )

不幸的是,我不断收到“aiohttp.client_exceptions.ClientConnectionError:连接已关闭”错误。似乎响应是在其上下文管理器之外读取的,但不确定如何解决这个问题。

有什么建议吗?

fastapi aiohttp
1个回答
0
投票

返回语句后上下文管理器关闭并且会话不再活动。

为了避免这种情况,您可以将会话创建移至生成器函数中:

@router.post("/")
async def proxy_stream():

    async def process_response():
        async with aiohttp.ClientSession() as http_session:
            async with http_session.post(
                "https://streaming-api",
                json={"json": "body"}
            ) as response:
                async for chunk in response.content.iter_chunked(128):
                    # Work on chunk and then stream it
                    yield process_chunk(chunk)

           
    return StreamingResponse(
        process_response()
    )

© www.soinside.com 2019 - 2024. All rights reserved.