Forums

MYSQL Connection Always Time Out After Few Minutes

My flask application when i reload and working on it, the mysql connection is just fine. However, if i left my application idle for a few minutes without any refresh, the application will show this error on the error log:

raise errors.OperationalError("MySQL Connection not available.")

How can I solve this? This is my current init.py configuration:

# app/__init__.py

# third-party imports
from datetime import timedelta
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
# local imports
from config import app_config
import logging
import os
# after existing third-party imports
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_bootstrap import Bootstrap
from flask_mail import Mail
# db variable initialization
db = SQLAlchemy()

# after the db variable initialization
login_manager = LoginManager()

mail=Mail()
UPLOAD_FOLDER = '/static/img/'
def create_app(config_name):
    app = Flask(__name__, instance_relative_config=True)
    SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username="winsonlee98",
    password="&password",
    hostname="winsonlee98.mysql.pythonanywhere-services.com",
    databasename="winsonlee98$flask",)
    app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_ENGINE_OPTIONS'] = { 'pool_pre_ping':True, 'pool_recycle' : 280}

    db = SQLAlchemy(app)



    #configuartion for email
    app.config.update(dict(
        DEBUG=True,
        MAIL_SERVER='smtp.gmail.com',
        MAIL_PORT=587,
        MAIL_USE_TLS=True,
        MAIL_USE_SSL=False,
        MAIL_USERNAME='$Username',
        MAIL_PASSWORD='&Password',
        MAIL_DEFAULT_SENDER='$Email'
    ))

    app.secret_key = 'otp';  #very very secret

    #with app.app_context():
    db.init_app(app)
    #db.create_all()
    app.config.from_pyfile('config.py')
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=5)
    db.init_app(app)
    Bootstrap(app)
    mail.init_app(app)
    login_manager.init_app(app)
    login_manager.login_message = "You must be logged in to access this page."
    login_manager.login_message_category = "danger"
    login_manager.login_view = "auth.login"
    migrate = Migrate(app, db,compare_type=True)


    from app import models

    #blueprint
    from .organization import organization as organization_blueprint
    app.register_blueprint(organization_blueprint, url_prefix='/organization')

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .home import home as home_blueprint
    app.register_blueprint(home_blueprint)

    @app.errorhandler(403)
    def forbidden(error):
        return render_template('errors/403.html', title='Forbidden'),403

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('errors/404.html', title='Page Not Found'), 404

    @app.errorhandler(500)
    def internal_server_error(error):
        return render_template('errors/500.html', title='Server Error')

    return app

Try removing the two calls to db.init_app(app) -- you don't need to do both that and also pass in app when you create the SQLAlchemy object, and I think they might be interfering with each other.

Thank you! This solved my issue!!!

Excellent, glad we could help :-)