sknat
sknat

Reputation: 478

Flask teardown_request happening before request sent

I have an issue with the @app.teardown_request decorator in Flask.

My code is looking like this

@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)

And when I go to the /entire endpoint, I get

 after
 teardown
 entire

When I go to the /chunked endpoint, I get

 chunked
 after
 teardown

So when returning the data in a chunky way, the request teardown is actually happening before I am returning any data (nor executing any code generating this data).

The data coming from a sqlalchemy session, I find my self closing the session before doing anything with the query - the behaviour I get is then getting idle in transaction all over the place...

Upvotes: 1

Views: 1128

Answers (1)

davidism
davidism

Reputation: 127320

Flask destroys the context when the response is returned, not after the generator runs. Use stream_with_context to keep the context around for the generator.

from flask import Response, stream_with_context

return Response(stream_with_context(gen(text)))

Upvotes: 1

Related Questions