Forums

MySQL Connection not available.

Hey, I updated yesterday to Innit Version. And also upgraded the python to 3.13 and everything was working fine. I checked database it was connected properly and working. Some python packages were missing, I installed them. But occasionally I am getting this:

2025-05-27 01:46:41,364: (Background on this error at: https://sqlalche.me/e/20/e3q8)
2025-05-27 01:46:41,364: Database error: (mysql.connector.errors.OperationalError) MySQL Connection not available.

I never faced this before. I haven't changed anything in my code. This is purely happening after upgrading. Any ideas?

Also, as I have said, sometimes the flask is able to connect to database and sometimes not. It's random and happening only now after upgrade.

Try adding pool_recycle to your db connection, see this help page.

Hey hi, yes I had this pool_recycle already added in my code like this:

app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
PERMANENT_SESSION_LIFETIME=timedelta(minutes=30),
SECRET_KEY=secrets.token_hex(32),  # Set SECRET_KEY directly
SQLALCHEMY_DATABASE_URI="mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username="",
    password="",
    hostname="",
    databasename="",
),
SQLALCHEMY_POOL_RECYCLE=299,
SQLALCHEMY_TRACK_MODIFICATIONS=False,)

As I said earlier, I am facing this only after updating to newer Python Version. Before it worked flawlessly. The code is intact, no changes there. Only variable that changed is the python version and ubuntu version.

Probably also all pre-installed packages verisions were modified. That includes sql alchemy, so your intact code may work differently.

Hey I think I may have fixed it using AI haha. I have done the following changes and it has worked... so far no connection issues:

app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
PERMANENT_SESSION_LIFETIME=timedelta(minutes=30),
SECRET_KEY=secrets.token_hex(32),
SQLALCHEMY_DATABASE_URI="mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username="",
    password="",
    hostname="",
    databasename="",
),
SQLALCHEMY_POOL_RECYCLE=280,  # Slightly lower than PythonAnywhere's 300s timeout
SQLALCHEMY_POOL_TIMEOUT=20,  # Maximum time to wait for a connection
SQLALCHEMY_POOL_SIZE=5,  # Maximum number of connections to keep
SQLALCHEMY_MAX_OVERFLOW=2,  # Maximum number of connections to create beyond pool_size
SQLALCHEMY_ENGINE_OPTIONS={
    "pool_pre_ping": True,  # Enable automatic connection testing
    "pool_reset_on_return": True,  # Reset connections when returned to pool
},
SQLALCHEMY_TRACK_MODIFICATIONS=False,
)

That's good to hear -- glad you sorted it out!

Yes! I can confirm that the issue has stopped totally.

Thanks for letting us know!