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)

最新更新