Flask teardown_request在请求发送之前发生

时间:2014-11-11 22:05:20

标签: python flask sqlalchemy flask-sqlalchemy

我在Flask中遇到@app.teardown_request装饰器问题。

我的代码看起来像这样

@app.teardown_request
def teardown_request(exception):
   print 'teardown'

@app.after_request
def after_request(response):
   print 'after'
   return response

@app.route('/entire', methods=['GET'])
def entire():
   print 'entire'
   return 'This is a text'

@app.route('/chunked', methods=['GET'])
def chunked():
   text = 'This is a text'
   def gen(t):
       print 'chunked'
       for a in t:
            yield a
   return gen(text)

当我进入/entire端点时,我得到了

 after
 teardown
 entire

当我转到/chunked端点时,我得到了

 chunked
 after
 teardown

因此,当以粗略的方式返回数据时,请求拆除实际上是在我返回任何数据之前发生的(也不执行生成此数据的任何代码)。

来自sqlalchemy会话的数据,我发现自己在对查询做任何事情之前关闭会话 - 我得到的行为然后到处都是idle in transaction ......

1 个答案:

答案 0 :(得分:1)

Flask在返回响应时销毁上下文,而不是在生成器运行后。使用stream_with_context保持生成器的上下文。

from flask import Response, stream_with_context

return Response(stream_with_context(gen(text)))