Flask-MySQL如何使用参数化查询有效地插入INTO表

时间:2017-01-14 15:45:18

标签: python mysql flask flask-mysql

我正在尝试使用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()
    
  • 在控制台中使用print语句调试代码:对于值得的东西,我也尝试打印如下所示的值,并且在我的控制台中不打印任何内容......这对我来说似乎很奇怪。 / p>

     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并遇到同样的问题。

2 个答案:

答案 0 :(得分:1)

尝试使用字典作为参数,它更具可读性:

params = {
    '_name' : request.form['inputName']
    '_email' : request.form['inputEmail']
    '_password' : request.form['inputPassword']
    '_username' : request.form['inputUsername']
}

然后:

query = """insert into tbl_user (user_name, user_username, user_password, user_email) 
         values (%(_name)s, %(_username)s, %(_password)s, %(_email)s)"""

cursor.execute(query, params)

答案 1 :(得分:1)

正如我在其中一条评论中提到的,创建该问题的原因是generate_hashed_pa​​ssword()函数。通过在StackOverflow中进行一些研究,我发现这个函数生成的字符串比原始密码长...所以我最终将我的MySQL表密码列从VARCHAR(45)更新为VARCHAR(100)并处理了问题