1

我一直在尝试解决这个问题一段时间。我尝试了所有我能找到的东西,但仍然一无所获。请帮忙。

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)

这是我的代码,它总是返回: 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、在导入MySQLdb文件“/usr/local/lib/python3.8/site-packages/MySQLdb/init.py ”,第24行,在version_info、 _mysql.version_info、_mysql中。文件

NameError:名称'_mysql'未定义

我正在使用来自 Visual Studio Code 的 macOS catalina、python 3.8.5。我已经安装了 MySQL prefpane、MySQL 客户端、MySQL 连接器。

4

1 回答 1

0

看起来您正在更早地初始化应用程序,您的代码应该如下所示

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)
于 2020-12-05T13:22:15.357 回答