【问题标题】:stream_with_context and stream_template raising a RuntimeErrorstream_with_context 和 stream_template 引发 RuntimeError
【发布时间】:2014-05-19 14:53:21
【问题描述】:

我正在使用以下文档: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

虽然我确实注意到文档明确指出 Without the stream_with_context() function you would get a RuntimeError at that point.,但我不明白为什么这会导致运行时错误,尽管已经包含了 stream_with_context

【问题讨论】:

    标签: python python-2.7 flask


    【解决方案1】:

    我并不完全熟悉您在stream_template 方法中所做的事情,但根据示例,您需要在Response 的第一个参数上使用stream_with_context,而不是围绕模板参数。

    如果您需要基于模板进行流式传输,那么模板可能需要成为生成函数的一部分。

    【讨论】:

      猜你喜欢
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      相关资源
      最近更新 更多