2

在回调函数中,我无法访问 flask.session、flask.g 或 url_for() 等函数。他们都抛出一个错误,说我“在请求上下文之外工作”。

Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):
  File "C:\Python27\site-packages\sijax\response\streaming.py", line 136, in _process_call_chain
    for string in generator:
  File "C:\Python27\site-packages\sijax\response\streaming.py", line 109, in _process_callback
    response = self._perform_handler_call(callback, args)
  File "C:\Python27\site-packages\sijax\response\base.py", line 258, in _perform_handler_call
    return callback(self, *args)
  File "C:\Dropbox\Code\Python 2.7\FlaskTesting\testpage.py", line 18, in myformhandler
    sql_session = flask.g.sql_session
  File "C:\Python27\lib\site-packages\werkzeug\local.py", line 336, in __getattr__
    return getattr(self._get_current_object(), name)
  File "C:\Python27\lib\site-packages\werkzeug\local.py", line 295, in _get_current_object
    return self.__local()
  File "C:\Python27\lib\site-packages\flask\globals.py", line 19, in _lookup_object
    raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
192.168.1.141 - - [20/Jun/2012 16:33:04] "POST /testpage HTTP/1.1" 200 -

我一直无法找出如何解决这个问题。任何帮助,将不胜感激。

  • Python v2.7
  • 烧瓶 v0.8
  • 烧瓶-Sijax v0.3
4

2 回答 2

1

您可以尝试使用 stream_with_context。从http://flask.pocoo.org/docs/0.12/patterns/streaming/#streaming-with-context复制的代码示例

from flask import stream_with_context, request, Response

@app.route('/stream')
def streamed_response():
    def generate():
        yield 'Hello '
        yield request.args['name']
        yield '!'
    return Response(stream_with_context(generate()))
于 2018-11-05T05:24:34.980 回答
0

如果您发布代码会很有帮助,但请尝试像这样包装您的代码:

with app.app_context():
    # do stuff...

或者这个:

with app.test_request_context():
    # do stuff...
于 2015-11-24T14:23:05.070 回答