问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/30521112/how-teardown-request-works-with-python-flask