Forums

Flask: mysql.connector.errors.OperationalError: MySQL Connection not available.

Problem: my application is seeing error "mysql.connector.errors.OperationalError: MySQL Connection not availabl" every few minutes.

This is super weird since I normally know how to handle such errors. I have read all the resources I can find but none of them works for me. To make it stranger, I have other applications on pythonanywhere.com and they are using exactly the same configs and they work well.

I'm using: Python 3.7 Flask: 1.0.2 SQLAlchemy: 1.2.10 Flask-SQLAlchemy: 2.3.2

I create flask app like this:

app = Flask(__name__)
app.config.from_object('config')
db.init_app(app)

db is created in another file:

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

And here are some related values in config.py

SQLALCHEMY_POOL_SIZE = 5
SQLALCHEMY_POOL_RECYCLE = 250

I just started this new app (still in dev, but not the free plan) and the database (MySql) is super small. I have only two simple queries so far:

from models import Post    
posts = Post.query.all()
post = Post.query.filter(Post.slug==slug).first_or_404()

To me obviously SQLALCHEMY_POOL_RECYCLE is not working as expected. I know SQLALCHEMY_POOL_RECYCLE is deprecated since flask-sqlalchemy 2.4 but I'm using 2.3. And all my other applications using the same packages and configs are working well.

Before upgrading flask-sqlalchemy, I really like to figure out what's wrong here.

Thanks for your help!

Is it possible that there are other processes apart from your web app that connect with this db and hold connections?

no, for now nothing else connecting to this db.

If it appears that SQLALCHEMY_POOL_RECYCLE is not working, the most likely cause of that is that the configuration was not applied for some reason. Make sure that the config file that you think you're using is, in fact, the config that you are using and make sure that the code to apply the config is actually being run. Also, a pool size of 5 is probably excessive. It's unlikely that you'll benefit from a poolsize greater than 1 and it could be holding connections open that do nothing except prevent other connections from being opened.