Problem: Flask app.teardown_appcontext is not being called when DEBUG is false. Flask's app.teardown_request works just fine.
Background: This problem was first discovered because of the error (2013, 'lost connection to mysql server during query') which was only happening when DEBUG = False
After looking into this further, I realized that this was because the session was not being removed properly in flask_sqlalchemy.
def create_app(config_obj):
app = Flask(__name__)
env = Environments(app)
env.from_object(config_obj)
# init extensions
SetupLogs(app)
db.init_app(app)
api.init_app(app)
CORS(app)
# This gets called after each request
@app.teardown_request
def teardown_request(response_or_exc):
db.session.remove()
# This never gets called after requests only when DEBUG = False!
@app.teardown_appcontext
def teardown_appcontext(response_or_exc):
db.session.remove()
return app
app = create_app('config')
manager = Manager(app)
migrate = Migrate(app, db)
...