我正在尝试使用 Flask 构建注册表单并尝试将用户条目提交到 MySQL 数据库。
使用参数化查询时我没有取得多大成功。这是我的 app.py 代码:
from flask import Flask, render_template, request, json
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash
mysql = MySQL()
app = Flask(__name__)
with open('config.json', 'r') as f:
config = json.load(f)
app.config['MYSQL_DATABASE_USER'] = config['user']
app.config['MYSQL_DATABASE_PASSWORD'] = config['password']
app.config['MYSQL_DATABASE_DB'] = config['database']
app.config['MYSQL_DATABASE_HOST'] = config['host']
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:
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
_username = request.form['inputUsername']
# validate the received values
if _name and _email and _password and _username:
conn = mysql.connect()
cursor = conn.cursor()
query = "select * from tbl_user where user_email = %s"
cursor.execute(query, (_email))
data = cursor.fetchall()
if len(data) is 0:
_hashed_password = generate_password_hash(_password)
query = "insert into tbl_user (user_name,user_username,user_password,user_email) values (%s,%s,%s,%s)"
cursor.execute(query, (_name, _username, _hashed_password, _email))
conn.commit()
return json.dumps({'message':'User created successfully !'})
else:
return json.dumps({'error':str(data[0]),
'message':'An account associated with this email address already exists.'
})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
except Exception as e:
return json.dumps({'error':str(e)})
finally:
cursor.close()
conn.close()
if __name__ == "__main__":
app.run(debug = True)
这是我到目前为止所尝试的:
硬编码值有效。我遇到的具体问题是这个查询。当我使用参数时它不起作用,但是当我使用硬编码值时它起作用。
query = "insert into tbl_user (user_name,user_username,user_password,user_email) values (%s,%s,%s,%s)" cursor.execute(query, (_name, _username, _hashed_password, _email)) conn.commit()
一个带有 1 个参数的简单查询:在下面的代码中,该参数可以正常工作并返回预期的结果,所以我很困惑为什么其他查询不起作用。
query = "select * from tbl_user where user_email = %s" cursor.execute(query, (_email)) data = cursor.fetchall()
在控制台中使用打印语句调试代码:对于什么值得,我也尝试打印如下所示的值,并且在我的控制台中不会打印任何内容......这对我来说似乎很奇怪。
if len(data) is 0: list_of_values = [_name, _username, _hashed_password, _email] print (list_of_values) _hashed_password = generate_password_hash(_password) query = "insert into tbl_user (user_name,user_username,user_password,user_email) values (%s,%s,%s,%s)" cursor.execute(query, (_name, _username, _hashed_password, _email)) conn.commit()
不同的 python - mysql 包:除了 Flask-MySQL,我还尝试过 PyMySQL 并遇到了同样的问题。