How can Flask / SQLAlchemy be configured to create a new database connection if one is not present?
I have an infrequently visited Python / Flask server which uses S
2018 answer: In SQLAlchemy v1.2.0+, you have the connection pool pre-ping feature available to address this issue of "MySQL server has gone away".
Connection pool pre-ping - The connection pool now includes an optional "pre ping" feature that will test the "liveness" of a pooled connection for every connection checkout, transparently recycling the DBAPI connection if the database is disconnected. This feature eliminates the need for the "pool recycle" flag as well as the issue of errors raised when a pooled connection is used after a database restart.
Pessimistic testing of connections upon checkout is possible with the new argument:
engine = create_engine("mysql+pymysql://user:pw@host/db", pool_pre_ping=True)