Search code examples
mysqlflaskmysql-pythonflask-mysql

How to fix KeyError: 'MYSQL_DATABASE_SOCKET' in Flask?


I have a Flask app and I want to connect MYSQL database and SELECT information from database. When I run my code, I encounter the following error:

KeyError: 'MYSQL_DATABASE_SOCKET

My code is:

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)

Can you help me?


Solution

  • You have to define MYSQL_DATABASE_SOCKET variable. In my case I use Config class that look like this:

    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'
    

    than pass it to you app object:

    app = Flask(__name__)
    app.config.from_object(Config)