stream_with_context 和 stream_template 抛出 RuntimeError
我正在参考以下文档:http://flask.pocoo.org/docs/patterns/streaming/。下面是错误追踪信息的一部分:
File "(my template)", line 85, in block "scripts"
{{ super() }}
File "/usr/local/lib/python2.7/site-packages/flask_bootstrap/templates/bootstrap/base.html", line 27, in block "scripts"
<script src="{{bootstrap_find_resource('jquery.js', cdn='jquery')}}"></script>
File "/usr/local/lib/python2.7/site-packages/flask_bootstrap/__init__.py", line 93, in bootstrap_find_resource
config = current_app.config
File "/usr/local/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/local/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/usr/local/lib/python2.7/site-packages/flask/globals.py", line 34, in _find_app
raise RuntimeError('working outside of application context')
这是我的代码:
@app.route('/render', methods=['GET', 'POST'])
def render():
form = MyForm(request.form)
if request.method == 'POST'
def generate():
for i,v in enumerate(my_data):
yield (i,v)
return Response(stream_template('results.html'), form=form, results=stream_with_context(generate))
else:
return render_template('advanced.html')
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
虽然我注意到文档里明确提到过 如果没有使用 stream_with_context() 函数,你会在那时遇到 RuntimeError。
,但我不明白为什么即使已经包含了 stream_with_context,还是会出现运行时错误。
1 个回答
0
我对你在 stream_template
方法里做的事情不是很了解,但根据这个例子,你需要在 Response
的第一个参数上使用 stream_with_context
,而不是在模板参数周围使用。
如果你想根据模板进行流式处理,那么可能需要把模板放在生成函数里。