Search code examples
python-3.xflaskresponseblueprint

Flask AttributeError: 'Blueprint' object has no attribute 'response_class'


I am trying to have my Flask route return a stream of text outputted from a log line by line back to my AJAX call like this:

my_app/auth/views.py:

@bp.route('/output_stream', methods=['GET', 'POST'])
def output_stream():
    def generate():
        if request.method == "POST":
            ...
            ...
            for line in iter(lambda: stdout.readline(2048), ""):
                data_buffer += line
                print(line, end="")
                yield line + '\n'
                if re.search(r'Done', line):
                    print('No more data')
                    break

            print('finished.')

            client.close()

    return bp.response_class(generate(), mimetype='text/plain')

I am registering my Flask app in __init__.py like this:

from flask import Flask

...
app = Flask(__name__)

...
...

from my_app.auth.views import bp
app.register_blueprint(bp)

However, it keeps throwing out Flask AttributeError: 'Blueprint' object has no attribute 'response_class' for some reason.

My Flask is up to date:

# pip install --upgrade Flask
Requirement already up-to-date: Flask in /usr/lib/python3.5/site-packages (1.0.2)

Does anyone know what might be the problem here?


Solution

  • Instead of:

    return bp.response_class(generate(), mimetype='text/plain')
    

    you probably want:

    from flask import Response, stream_with_context
    # in output_stream:
    return Response(stream_with_context(generate()), mimetype='text/plain')
    

    The stream_with_context is required because you access request inside the generator.