Python loses connection to MySQL database after about a day Python loses connection to MySQL database after about a day flask flask

Python loses connection to MySQL database after about a day


I have it working now. Using pooled connections seemed to fix the issue for me.

mysql.connector.connect(    host='10.0.0.25',    user='xxxxxxx',     passwd='xxxxxxx',     database='xxxxxxx',    pool_name='batman',    pool_size = 3)def connection():    """Get a connection and a cursor from the pool"""    db = mysql.connector.connect(pool_name = 'batman')    return (db, db.cursor())

I call connection() before each query function and then close the cursor and connection before returning. Seems to work. Still open to a better solution though.

Edit

I have since found a better solution. (I was still occasionally running into issues with the pooled connections). There is actually a dedicated library for Flask to handle mysql connections, which is almost a drop-in replacement.

From bash: pip install Flask-MySQL

Add MYSQL_DATABASE_HOST, MYSQL_DATABASE_USER, MYSQL_DATABASE_PASSWORD, MYSQL_DATABASE_DB to your Flask config. Then in the main Python file containing your Flask App object:

from flaskext.mysql import MySQLmysql = MySQL()mysql.init_app(app)

And to get a connection: mysql.get_db().cursor()

All other syntax is the same, and I have not had any issues since. Been using this solution for a long time now.