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.

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.