Python Flask-Mysql KeyError: 'MYSQL_HOST'

Python Flask-Mysql KeyError: 'MYSQL_HOST'

我正在构建一个 python flask-Mysql 应用程序。我正在使用 AWS cloud9 构建它。但是当我 运行 代码时,我得到 MYSQL_HOST 键错误。 我在下面附上代码。 是安装错误还是代码错误?`

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)

`

您正在呼叫 application = Flask(__name__) 两次。所以第二次你覆盖了第一个application。应该是:

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)