webminal.org
webminal.org

Reputation: 47276

How teardown_request() works with Python- Flask?

I received internal error with message:

"TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30"

and searching online gave teardown_request() solution :

@app.teardown_request
def checkin_db(exc):
    try:
        print "Removing db session."
        db.session.remove()
    except AttributeError:
        pass

Now timeout error is gone. But I didn't understand teardown_request completely, look like db.session.remove() will be invoked after every request ? or every error? Is it safe to use this code?

Upvotes: 10

Views: 18672

Answers (1)

junnytony
junnytony

Reputation: 3525

teardown_request registers a function to be called at the end of each request whether it was successful or an exception was raised. It is a good place to cleanup request scope objects like a database session/transaction. That is all your code sample is doing.

It is safe to use that code and db.session.remove() will be called after every request (even if an exception occurs during the request)

See Flask Callbacks and Errors and Flask.teardown_request for more information

Upvotes: 16

Related Questions