我试图使用Flask-MySQLdb。每次我去一个页面时都会收到错误_mysql_exceptions.ProgrammingError: closing a closed connection
。为什么这不起作用?
from flask import Flask, render_template, request, json
from flask_mysqldb import MySQL
application = Flask(__name__)
mysql = MySQL(application)
application.config['MYSQL_USER'] = 'root'
application.config['MYSQL_PASSWORD'] = 'password'
application.config['MYSQL_DB'] = 'db name'
application.config['MYSQL_HOST'] = 'localhost'
mysql.init_app(application)
@application.route('/')
def index():
cur = mysql.connection.cursor()
cur.execute("SHOW TABLES")
rv= cur.fetchall()
return str(rv)
if __name__ == "__main__":
application.run()
答案 0 :(得分:1)
您已在同一应用程序上初始化扩展程序两次。每次初始化时,它都会注册一个关闭连接的函数。因此,第二个函数关闭已由第一个注册函数关闭的连接。从application
移除MySQL
(最好)或移除对mysql.init_app
的显式调用。
mysql = MySQL()
mysql.init_app(application)