Python Flask SQL 注册登录页面 "hash must be unicode or bytes, not long"

Python Flask SQL Register Login Page "hash must be unicode or bytes, not long"

我正在尝试创建登录/注册页面。我的注册页面有效,我看到添加的信息和散列密码。当我尝试登录时,出现 "hash must be unicode or bytes, not long" 闪烁。请帮忙!

    @app.route('/login/', methods=['GET','POST'])
    def login():
        try:
            c,conn = connection()

            if request.method == 'POST':

                data = c.execute("SELECT * FROM users WHERE username = %s",
                        thwart(request.form['username']))

                if sha256_crypt.verify(request.form['password'], data):
                    session['logged_in'] = True
                    session['username'] = request.form['username']
                    flash('You are now logged in.'+str(session['username']))
                    return redirect(url_for('dashboard'))

            else:
                error = 'Invalid credentials. Try again'

            return render_template('login.html', error=error)
        except Exception, e:
                flash(e)
------------------------------------------------------------------

     import MySQLdb

     def connection():
         conn = MySQLdb.connect(host="localhost",
                                user = "root",
                                passwd = "julie774",
                                db = "PYTHONTUT")
         c = conn.cursor()

         return c, conn

data = c.execute("SELECT * FROM users WHERE username = %s", thwart(request.form['username']))

cursor.execute 只执行查询,returns 受影响的行数。 (参见 cursor.execute 的 pydoc)。因此,在您的 data 变量中,您有找到的行数。

相反,您必须从游标中获取数据。此外,由于您正在请求用户 (*) 的所有列,因此您将只需要提取一个特定的列(它的索引——见尾注)。

c.execute("SELECT password FROM users WHERE username = %s",
                    thwart(request.form['username']))
data = c.fetchone()
# c.fetchone() returns None if no row has been found

if sha256_crypt.verify(request.form['password'], data[0]):
    ...

在您的示例中,您连接到数据库时未指定游标类型,因此 c.fetchone() 将 return 一个元组(例如 (1L, 'John Doe', '392347'))。对于 select 特定列,您必须使用数字索引 — data[1] 来检索 'John Doe'.

如果您想要命名字典,则必须在连接到数据库时指定它。

conn = MySQLdb.connect(host="localhost",
                       user = "root",
                       passwd = "***",
                       db = "PYTHONTUT",
                       cursorclass=MySQLdb.cursors.DictCursor
                       )

然后 c.fetchone() 将 return 改为 dict(例如 {'id': 1L, 'name': 'John Doe', 'password': '392347'}),因此您可以使用更具可读性的 data['name']