1

我正在构建一个 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)

`

4

1 回答 1

1

你打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)
于 2021-07-21T05:09:54.600 回答