Stream response with AsyncGenerator #5616
Replies: 2 comments 5 replies
-
|
@LorenzoVaccher01 Hello, is there any progress regarding this issue? I encountered a similar problem when trying to integrate the asynchronous streaming agent execution in Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):
File "C:\Users\pengz\AppData\Roaming\Python\Python310\site-packages\werkzeug\wsgi.py", line 256, in __next__
return self._next()
File "C:\Users\pengz\AppData\Roaming\Python\Python310\site-packages\werkzeug\wrappers\response.py", line 32, in _iter_encoded
for item in iterable:
TypeError: 'async_generator' object is not iterable |
Beta Was this translation helpful? Give feedback.
-
|
I ran into a similar issue a while back. I was trying to stream from an async generator via import asyncio
from typing import AsyncGenerator, Callable
def stream_helper(async_gen_factory: Callable[[], AsyncGenerator[str, None]]):
def _stream():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
agen = async_gen_factory()
try:
while True:
try:
chunk = loop.run_until_complete(agen.__anext__())
except StopAsyncIteration:
break
yield chunk
finally:
loop.run_until_complete(agen.aclose())
loop.close()
return _stream()Drop in for your case from Flask import Response
@message_route.route('/message/<string:key>/<string:chat_uuid>', methods=['POST'])
async def message(key, chat_uuid):
# [...]
return Response(
stream_helper(event_stream()),
content_type="text/event-stream",
) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I would need to stream data to the user via an endpoint through a function that returns an AsyncGenerator
The idea is as follows:
To be able to handle requests with async/await I installed
flask[async](3.0.3) but when I add async to themessage()function I get the error:Beta Was this translation helpful? Give feedback.
All reactions