3

I am rendering a template by streaming data from a Flask view. When I do not use url_for, the page works correctly. If I add url_for, I get RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.

I tried the answer in Flask.url_for() error: Attempted to generate a URL without the application context being pushed, but I still get the error after adding app.config['SERVER_NAME'] = 'localhost:5000'

How can I generate urls in the streamed template, preferably without setting SERVER_NAME or hardcoding the path?

<!doctype html>
<html>
<head>
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.png') }}">
</head>
<body>
    {% for number in data %}
    <script>
        console.log(JSON.parse({{ number|tojson }}));
    </script>
    {% endfor %}
</body>
</html>
from flask import Flask, json

app = Flask(__name__)

def stream_template(template_name, **context):
    app.update_template_context(context)
    t = app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    rv.enable_buffering(5)
    return rv

@app.route('/')
def main():
    def generate():
        for number in range(10):
            yield json.dumps(number)

    return Response(stream_template('index.html', data=generate()))

if __name__ == '__main__':
    app.run(debug=True)
Community
  • 1
  • 1
Jonas
  • 1,473
  • 2
  • 13
  • 28

0 Answers0