2

I've been trying to solve this problem for a while now. I tried everything I can find and still nothing. Kindly help.

from flask import Flask, request, jsonify
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSOWRD'] = 'password'
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_DB'] = 'try_flask'

app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

mysql = MySQL(app)

if __name__ == '__main__':
    app.run(debug=True)

@app.route('/employee', methods=['GET','POST'])
def employee():
    if request.method == 'GET':
        cur = mysql.connection.cursor()
        cur.execute('''SELECT * FROM employee''')
        results = cur.fetchall()
    return jsonify(results)

This is my code, and it always return: File "app1.py", line 3, in from flask_mysqldb import MySQL File "/usr/local/lib/python3.8/site-packages/flask_mysqldb/init.py", line 1, in import MySQLdb File "/usr/local/lib/python3.8/site-packages/MySQLdb/init.py", line 24, in version_info, _mysql.version_info, _mysql.file

NameError: name '_mysql' is not defined

I'm using macOS catalina, python 3.8.5 from Visual Studio Code. I have MySQL prefpane, MySQL client, MySQL connector all installed.

theguy
  • 21
  • 1
  • 2

1 Answers1

0

It looks like you are initializing app bit earlier your code should looks like this

from flask import Flask, request, jsonify
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSOWRD'] = 'password'
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_DB'] = 'try_flask'

app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

mysql = MySQL(app)

@app.route('/employee', methods=['GET','POST'])
def employee():
    if request.method == 'GET':
        cur = mysql.connection.cursor()
        cur.execute('''SELECT * FROM employee''')
        results = cur.fetchall()
    return jsonify(results)
## i saw everywhere app started at then end of app.py
if __name__ == '__main__':
    app.run(debug=True)
Mansur Ul Hasan
  • 2,898
  • 27
  • 24
  • Thank you for your reply! Somehow after I update my python the code works! I think there were some error between my python and sql. – theguy Dec 07 '20 at 02:32