how to use streaming response with anyio stream queue properly #12061
-
First Check
Commit to Help
Example Codesend_stream, recv_stream = create_memory_object_stream[bytes]()
tg = create_task_group()
await tg.__aenter__()
tg.start_soon(generate_messages, send_stream)
async def response_stream():
async with recv_stream:
async for message in recv_stream:
yield message
return StreamingResponse(response_stream(), background=BackgroundTask(tg.__aexit__))DescriptionI used to above code to generate the streaming response, my question is is there a simpler way to fire the previously I just using the so I'm thinking the use a simpler queue method as the generator, hopefully to reduce the error and ease the maintenace. Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.112.1 Pydantic Version2.8.2 Python VersionPython 3.11.9 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
I think you don't need that construction. You can just put To avoid such problems, you should catch specific exceptions instead of all exceptions. |
Beta Was this translation helpful? Give feedback.
I think you don't need that construction. You can just put
generate_messagesintoStreamingResponse.The reason why you had
async generator ignored GeneratorExiterror was likely that you were catching all the exceptions (except Exception:).To avoid such problems, you should catch specific exceptions instead of all exceptions.
Or, you can start with adding except block to re-raise
GeneratorExit: