From daba67611b59102e6e60a911decb6b13c2fc5a8f Mon Sep 17 00:00:00 2001 From: Thomas M Steenholdt Date: Tue, 12 Jun 2018 14:00:21 -0200 Subject: [PATCH] Enable pool_pre_ping in DB connection To avoid problems with inactive DB connections, SQLAlchemy provides a `pool_pre_ping` option, that described in more detail here: http://docs.sqlalchemy.org/en/latest/core/pooling.html#disconnect-handling-pessimistic In flask environments, it's enabled by subclassing SQLAlchemy, which is what I've done here. Fixes errors like: sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2006, 'MySQL server has gone away') which results in an Error 500 in the UI. --- app/__init__.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index c309b78..c5a8bcc 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,15 @@ from werkzeug.contrib.fixers import ProxyFix from flask import Flask, request, session, redirect, url_for from flask_login import LoginManager -from flask_sqlalchemy import SQLAlchemy +from flask_sqlalchemy import SQLAlchemy as SA + + +# subclass SQLAlchemy to enable pool_pre_ping +class SQLAlchemy(SA): + def apply_pool_defaults(self, app, options): + SA.apply_pool_defaults(self, app, options) + options["pool_pre_ping"] = True + app = Flask(__name__) app.config.from_object('config')