在回调函数中,我失去了访问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 -
我一直无法找到如何解决这个问题。任何帮助将不胜感激。
答案 0 :(得分:0)
如果您发布了代码,但尝试将代码包装起来会很有帮助:
with app.app_context():
# do stuff...
或者这个:
with app.test_request_context():
# do stuff...
答案 1 :(得分:0)
您可以尝试使用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()))