Flask Stream Helpers API

stream_with_contextUsed to maintain the request context in generator functions, so that objects such as request and session remain accessible during streaming responses.


stream_with_context

Parameter Type Description
generator_or_function iterator / callable A generator function or callable object. Used as a decorator or wrapper function.

Two usage modes

Usage Description
Decorator mode @stream_with_context decorates the generator function
Wrapper mode stream_with_context(generator()) wraps an already-created generator

Notes: Once the response body begins to be sent, the response headers can no longer be modified. If the generator needs to access the session, you must first access the session in the view function to trigger the setting of the Vary: Cookie header.


Code Examples

Example

from flask import Flask, stream_with_context, request, Response

app = Flask(__name__)

@app.get("/stream")
def streamed_response():
    """Streaming response example: send data line by line"""
    @stream_with_context
    def generate():
        # Even after the response has started sending, request can still be accessed
        yield f"data: Hello {request.args.get('name', 'EXAMPLE')}\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 mode"""
    def generate():
        yield "Hello "
        yield request.args.get("name", "World")
        yield "!"

    # Use stream_with_context to wrap the generator that has already been created
    return Response(stream_with_context(generate()))
other extensions