Flask Stream Helpers API
stream_with_context is used to preserve the request context inside a generator function, so that objects such as request and session remain accessible in a streaming response.
stream_with_context
| Parameters | Type | Description |
|---|---|---|
| generator_or_function | iterator / callable | A generator function or callable. Used as a decorator or a wrapper function |
Two usage patterns
| Usage | Description |
|---|---|
| Decorator pattern | @stream_with_context decorates a generator function |
| Wrapper pattern | stream_with_context(generator()) wraps an already-created generator |
Notes: Once the response body starts being sent, the response headers can no longer be modified. If the generator needs to access session, you must access session first in the view function to trigger the setting of the Vary: Cookie header.
Code Example
Example
from
flask
import
Flask
,
stream_with_context
,
request
,
Response
app
=
Flask
(
name
)
@
app.
get
(
"/stream"
)
def
streamed_response
(
)
:
"""Streaming response example: Sending data line by line"""
@
stream_with_context
def
generate
(
)
:
request remains accessible even after the response has started sending
yield
f
"data: Hello {request.args.get('name', 'RUNOOB')}\n"
for
i
in
range
(
5
)
:
yield
f
"data: Line {i}\n"
yield
"data: [DONE]\n"
return
Response
(
generate
(
)
,
mimetype
=
"text/event-stream"
)
@
app.
get
(
"/stream-wrap"
)
def
stream_wrap
(
)
:
"""Wrapper pattern"""
def
generate
(
)
:
yield
"Hello "
yield
request.
args
.
get
(
"name"
,
"World"
)
yield
"!"
Use stream_with_context to wrap an already-created generator
return
Response
(
stream_with_context
(
generate
(
)
)
)