9

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?

webminal.org
  • 44,948
  • 37
  • 94
  • 125
  • 1
    How are you opening connections? Are you closing them after your tx is completed? Are you using Flask-SQLAlchemy module? Are you creating your own session? – Boris May 29 '15 at 04:53
  • thanks for the response. After setting password details, connection is established via "db = SQLAlchemy(app)" If each request is Tx , then yes. Like closing them after '/login' , but user can access '/profile' page without any issues. Yes, Flask SqlAchemy module is used. The code relies on Flask session. We don't create own sessions. – webminal.org May 30 '15 at 14:15

1 Answers1

14

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

Michael
  • 713
  • 10
  • 27
junnytony
  • 3,455
  • 1
  • 22
  • 24
  • Just one quick question, Say user logged into the site, now db.session.remove() will be invoked? Then how he/she is able to access his 'profile settings' page without need to re-login? – webminal.org May 30 '15 at 14:16
  • 2
    db.session.remove() just cleans up database session not Flask session. Flask session is by default stored in a cookie which is passed from the client with each request. db.session.remove() makes sure any database transactions you were doing either committed successfully or rolled back – junnytony May 30 '15 at 19:26
  • 2
    What is the difference between `@app.teardown_request` and `@app.teardown_appcontext`? – Martin Thoma Sep 22 '17 at 07:30
  • @junnytony when do we really implement teardown request i.e if done during app development stage, if there is a bug it will never get resolved is my concern until unless we log the exception and check it regularly – user956424 Jan 06 '18 at 07:40