How to fix KeyError: 'MYSQL_DATABASE_SOCKET' in Flask?
How to fix KeyError: 'MYSQL_DATABASE_SOCKET' in Flask?
我有一个 Flask
应用程序,我想连接 MYSQL
数据库和来自数据库的 SELECT
信息。当我 运行 我的代码时,遇到以下错误:
KeyError: 'MYSQL_DATABASE_SOCKET
我的代码是:
from flaskext.mysql import MySQL
import pymysql
from flask import render_template, redirect
app = Flask(__name__)
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'market_DB'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_PORT'] = '3306'
mysql.init_app(app)
@app.route('/')
def product():
conn = mysql.connect()
cursor = conn.cursor()
#return "ok"
cursor.execute("SELECT * FROM Tbl_product")
productDetails= cursor.fetchall()
return render_template('product.html', productDetails=productDetails)
if __name__ == '__main__':
app.run(debug=True)
你能帮帮我吗?
您必须定义 MYSQL_DATABASE_SOCKET 变量。在我的例子中,我使用如下所示的 Config class:
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
MYSQL_DATABASE_USER = 'root'
MYSQL_DATABASE_PASSWORD = 'root'
MYSQL_DATABASE_DB = 'flask'
MYSQL_DATABASE_HOST = 'localhost'
MYSQL_DATABASE_SOCKET = '/tmp/mysql.sock'
比将它传递给您的应用程序对象:
app = Flask(__name__)
app.config.from_object(Config)
app.config['MYSQL_DATABASE_SOCKET'] = None
我有一个 Flask
应用程序,我想连接 MYSQL
数据库和来自数据库的 SELECT
信息。当我 运行 我的代码时,遇到以下错误:
KeyError: 'MYSQL_DATABASE_SOCKET
我的代码是:
from flaskext.mysql import MySQL
import pymysql
from flask import render_template, redirect
app = Flask(__name__)
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'market_DB'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_PORT'] = '3306'
mysql.init_app(app)
@app.route('/')
def product():
conn = mysql.connect()
cursor = conn.cursor()
#return "ok"
cursor.execute("SELECT * FROM Tbl_product")
productDetails= cursor.fetchall()
return render_template('product.html', productDetails=productDetails)
if __name__ == '__main__':
app.run(debug=True)
你能帮帮我吗?
您必须定义 MYSQL_DATABASE_SOCKET 变量。在我的例子中,我使用如下所示的 Config class:
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
MYSQL_DATABASE_USER = 'root'
MYSQL_DATABASE_PASSWORD = 'root'
MYSQL_DATABASE_DB = 'flask'
MYSQL_DATABASE_HOST = 'localhost'
MYSQL_DATABASE_SOCKET = '/tmp/mysql.sock'
比将它传递给您的应用程序对象:
app = Flask(__name__)
app.config.from_object(Config)
app.config['MYSQL_DATABASE_SOCKET'] = None