How teardown_request() works with Python- Flask?

时间秒杀一切 提交于 2019-12-24 03:10:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!