以下是我一直在为烧瓶中的python web开发工作的教程中的代码:
from flask import Flask, render_template, json, request
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash
app = Flask(__name__)
mysql = MySQL(app)
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'PhoneList'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
@app.route("/")
def main():
return render_template('index.html')
@app.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
@app.route('/signUp', methods = ['POST','GET' ])
def signUp():
try:
_phonenumber = request.form['phonenumber']
_name = request.form['name']
_password = request.form['password']
if _phonenumber and _name and _password:
conn = mysql.connect()
cursor = conn.cursor()
_hashed_password = generate_password_hash(_password)
cursor.callproc('sp_createphoneuser',(_phonenumber,_name,_hashed_password))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return json.dumps({'message':"User created successfully !"})
else:
return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
except Exception as e:
return json.dumps({'error':str(0)})
finally:
cursor.close()
conn.close()
if __name__ == "__main__":
app.debug = True
app.run(port=5002)
当我运行这个并转到localhost站点时,我得到“网页不可用”,并在我的终端上显示一条消息“Programmingerror关闭一个隐藏的标题”
我无法弄清楚我在这里搞砸了什么..我是python web开发的新手,所以我希望我不会在这里问一个非常愚蠢的问题。
由于
答案 0 :(得分:1)
我重现了这个错误,看起来你正在初始化两次数据库驱动程序,看看:
mysql = MySQL(app)
....config stuff
mysql.init_app(app)
现在查看库代码:
class MySQL(object):
def __init__(self, app=None, **connect_args):
self.connect_args = connect_args
if app is not None:
self.app = app
self.init_app(self.app)
else:
self.app = None
def init_app(self, app):
self.app = app
...some more code
self.app.teardown_request(self.teardown_request)
self.app.before_request(self.before_request)
现在当您再次调用 init_app 时,您正在关闭已经打开的连接,当您调用MySQL的构造函数时,应用对象参数。
将两行中的一行更改为:
mysql = MySQL()
#config stuff, and then init the app
mysql.init_app(app)
或
#config stuff
mysql = MySQL(app)
这必须解决问题