StreamingResponse with async generator sometimes causes socket.send() exception indefinitely #6260
-
First Check
Commit to Help
Example Codeimport asyncio
import uvicorn
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
def sync_streamer():
try:
while True:
yield b"--boundary\r\nContent-Type: text/plain\r\nContent-Length: 1\r\n\r\n1\r\n"
except asyncio.CancelledError:
print("caught cancelled error")
async def async_streamer():
try:
while True:
yield b"--boundary\r\nContent-Type: text/plain\r\nContent-Length: 1\r\n\r\n1\r\n"
except asyncio.CancelledError:
print("caught cancelled error")
@app.get("/sync")
async def sync_endpoint():
return StreamingResponse(
sync_streamer(),
media_type="multipart/x-mixed-replace; boundary=boundary",
)
@app.get("/async")
async def async_endpoint():
return StreamingResponse(
async_streamer(),
media_type="multipart/x-mixed-replace; boundary=boundary",
)DescriptionWhen I try to send data with a StreamingResponse from an infinite generator I sometimes get an error when the generator is asynchronous. Sometimes it works fine, but sometimes I get an infinite stream of errors: I've based my sample code on #4146 and the It could be that this is a Starlette issue but I am really not sure. Operating SystemLinux Operating System DetailsNo response FastAPI Version0.79.0 Python Version3.8.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
|
Even |
Beta Was this translation helpful? Give feedback.
-
|
What's the exception?
If you can reproduce with a pure Starlette application, then I'd invite you to create a discussion on Starlette's side. 🙏 |
Beta Was this translation helpful? Give feedback.
-
No exceptions at all, it's stuck endlessly. I'll do that! |
Beta Was this translation helpful? Give feedback.
-
|
@MichadeGroot as per @Kludex there is no The solution for it is here Kludex/starlette#1776 (comment) |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
@MichadeGroot as per @Kludex there is no
awaitin your async generators, so all other tasks in task groups are waiting endlesssly for it to complete.The solution for it is here Kludex/starlette#1776 (comment)