closing mysql database connection in python flask application

55 Views Asked by At

This Python / Flask / MySQL web application is used to help a business change the message on their advertising signs.

I recently upgraded my heroku mysql database to cleardb. Lately I cannot run the application because it keeps giving me the error message

MySQLdb.OperationalError: (1226, "User 'b6e526988cfe5a' has exceeded the 'max_user_connections' resource (current value: 15)")

I have put try-finally blocks in each of my functions to ensure the connection is closed every time, yet I still get this error. Where am I going wrong? I tried using conn.close() in the finally block, but then it gives me a "2006" error.

from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from flask_mysqldb import MySQL
from werkzeug.security import check_password_hash, generate_password_hash

# using login required from helpers from the "Finance" problem set
from helpers import login_required, check_available_chars

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.secret_key = [CENSORED]
app.config["SESSION_PERMANENT"] = True
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

app.config['MYSQL_HOST'] =  [CENSORED]
app.config['MYSQL_USER'] =  [CENSORED]
app.config['MYSQL_PASSWORD'] =  [CENSORED]
app.config['MYSQL_DB'] =  [CENSORED]
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
app.config['MYSQL_CHARSET'] = 'utf8mb4'

mysql = MySQL(app)

# Sample function

@app.route("/change", methods=["GET"])
@login_required
def change():
    
    conn = mysql.connection
    cur = conn.cursor()
    
    try:
        cur.execute("SELECT doubleSided, prevMessage1, prevMessage2 from businesses WHERE businessID = %s", (int(session['user_id']),))
        currentMessageData = cur.fetchall()[0]
        doubleSided = True if int(currentMessageData['doubleSided']) == 1 else False
        if doubleSided:
            currentMessages = [currentMessageData['prevMessage1'],currentMessageData['prevMessage2']]
        else:
            currentMessages = [currentMessageData['prevMessage1']]

        cur.close()
        
        return render_template("change.html", doubleSided=doubleSided, currentMessages=currentMessages)
    finally:
        cur.close()

0

There are 0 best solutions below