在Flask中使用流式传输模板时使用url_for会引发RunTimeError

时间:2017-02-17 23:14:19

标签: python flask jinja2

我通过从Flask视图流式传输数据来渲染模板。当我不使用url_for时,页面正常工作。如果我添加url_for,我会收到RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.

我在Flask.url_for() error: Attempted to generate a URL without the application context being pushed中尝试了答案,但在添加app.config['SERVER_NAME'] = 'localhost:5000'后仍然出现错误

如何在流式模板中生成网址,最好不设置SERVER_NAME或硬编码路径?

<!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)

0 个答案:

没有答案