Skip to content
Advertisement

Python Flask-Mysql KeyError: ‘MYSQL_HOST’

I am building a python flask-Mysql app. I am building it using AWS cloud9. But When I run the code I am geting MYSQL_HOST key error. I am attaching code below. Is it because of the installation fault or code error.?`

from flask import Flask, request, render_template
from flask_mysqldb import MySQL


application = Flask(__name__)

application.config['MYSQL_HOST'] = 'localhost'
application.config['MYSQL_USER'] = 'nfhfjfn'
application.config['MYSQL_PASSWORD'] = 'fsfc'
application.config['MYSQL_DB'] = 'fsvf'
application.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(application)
# mysql.init_app(application)

application = Flask(__name__)

@application.route("/")
def hello():
    cursor = mysql.connect().cursor()
    cursor.execute("SELECT * from LANGUAGES;")
    mysql.connection.commit()
    languages = cursor.fetchall()
    languages = [list(l) for l in languages]
    return render_template('index.html', languages=languages)
    
    
if __name__ == "__main__":
    application.run(host='0.0.0.0',port=8080, debug=True)

`

Advertisement

Answer

You are calling application = Flask(__name__) twice. So second time you are overwriting the first application. It should be:

from flask import Flask, request, render_template
from flask_mysqldb import MySQL


application = Flask(__name__)

application.config['MYSQL_HOST'] = 'localhost'
application.config['MYSQL_USER'] = 'nfhfjfn'
application.config['MYSQL_PASSWORD'] = 'fsfc'
application.config['MYSQL_DB'] = 'fsvf'
application.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(application)
# mysql.init_app(application)

#application = Flask(__name__) <--- remove that

@application.route("/")
def hello():
    cursor = mysql.connect().cursor()
    cursor.execute("SELECT * from LANGUAGES;")
    mysql.connection.commit()
    languages = cursor.fetchall()
    languages = [list(l) for l in languages]
    return render_template('index.html', languages=languages)
    
    
if __name__ == "__main__":
    application.run(host='0.0.0.0',port=8080, debug=True)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement