Stream read and stream response "hangs", returns 327 bytes of 10 megabytes #11566
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI
from fastapi.responses import Response, StreamingResponse
import logging
import aiohttp
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
app = FastAPI()
async def async_request(): #
async with aiohttp.ClientSession() as client:
logging.info("Start get")
r = client.get(url="https://mirror.aarnet.edu.au/pub/debian-cd/12.5.0/amd64/iso-cd/debian-12.5.0-amd64-netinst.iso",
headers={"Range": f"bytes=0-{1024*1024*10}"})
logging.info("After get")
return await r
@app.get("/")
async def main():
logging.info("Start main/return")
r = await async_request()
return StreamingResponse(r.content) DescriptionI would expect the above code to return 10 megabytes of the file, hopefully streaming the request to the response directly Instead, the response starts successfully, but stops after 327 bytes Please forgive the contrived example, this works to demonstrate the issue
(curl hangs until timeout) Sidenote: this doesn't work at all in httpx, which can't produce a stream response that either asyncio or FastAPI can cope with. I might open another discussion about that one Operating SystemLinux, Windows Operating System DetailsNo response FastAPI Version0.111.0 Pydantic Version2.7.1 Python Version3.11.2 / 3.12.2 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
...this should probably be an issue, shouldn't it? |
Beta Was this translation helpful? Give feedback.
When you do
return await r
inasync_request
, you return StreamRead object, but at the same time you close client session, that is used by that StreamRead object (when you callreturn
you exit from context managerasync with aiohttp.ClientSession() as client:
)So, you need to turn your
async_request
into async generator and iterate throughr.content
inside: