TypeError:强制转换为Unicode:需要字符串或缓冲区,找到sqlite3.Cursor

时间:2018-05-19 19:50:23

标签: python sqlite flask

我正在使用Flask和SQLite作为数据库构建Python Web应用程序。

当我尝试登录并验证数据库中的用户信息时,我收到上述错误。我的其他数据库表单输入工作,我能够更新和选择数据,因此数据库存在,连接在应用程序的某些部分工作。登录脚本似乎是个问题。

@app.route('/login', methods=['POST', 'GET'])
def do_admin_login():
if request.method == "POST":
u_stmt="SELECT CASE WHEN '"+ request.form['username'] +"' IN (SELECT uname 
FROM logins) THEN 1 ELSE 0 END"  #uname in logins
p_stmt="SELECT pword FROM logins WHERE uname = '"+request.form['username']+"'"  
# retrieve pwd of uname
s_stmt="SELECT salt FROM logins WHERE uname = '"+request.form['username']+"'"  
# retrieve salt of uname
print u_stmt
print p_stmt
print s_stmt
with sql.connect("database.db") as con:
  cur = con.cursor()
  pwd = cur.execute(p_stmt)
  uname = cur.execute(u_stmt)
  salt = cur.execute(s_stmt)
  print uname
  print pwd
  print salt
  con.commit()
con.close()

hashed_password = hash_password(request.form['password'], salt)
if hashed_password == pwd and uname == 1:
    session['logged_in'] = True     
    flash('right password!')
    return render_template('home.html')
else:
    flash('wrong password!')
return home()
else:
return render_template('login.html')

以下是我的login.html

中的代码
<form action="/login" method="POST">
<div class="login">
    <div class="login-screen">
        <div class="app-title">
            <h1>Login</h1>
        </div>

        <div class="login-form">
            <div class="control-group">
            <input type="text" class="login-field" value="" placeholder="username" name="username">
            <label class="login-field-icon fui-user" for="login-name"></label>
            </div>

            <div class="control-group">
            <input type="password" class="login-field" value="" placeholder="password" name="password">
            <label class="login-field-icon fui-lock" for="login-pass"></label>
            </div>

            <button type="submit" class="btn btn-primary btn-large btn-block">Log in</button>
            <br><br>
            <a href="signup" class="btn btn-primary btn-large btn-block">Sign up</a>
            <br><br>
        </div>
    </div>
</div>

Stacktrace (methinks)

非常感谢任何帮助。谢谢!

def hash_password(password, salt):
"""
Take a password and a salt, and return a hashed password
"""
password_string = (password + salt).encode('utf-8')
hashed_password = hashlib.sha512(password_string).hexdigest()
return hashed_password


def get_auth_for_user(user_id):
"""
Take a user_id, and return what we know about that user
"""
db_cursor.execute("SELECT * FROM user WHERE id=" + user_id)
result = db_cursor.fetchone()
return result

Traceback with SQL output

1 个答案:

答案 0 :(得分:0)

这里的主要问题是你试图强迫sqlite3.Cursor对象进行unicode。

语句salt = cur.execute(s_stmt)返回sqlite3.Cursor个对象(请注意,日志中print salt语句的输出为<sqlite3.Cursor object at 0x1048e1500>

更改此行: salt = cur.execute(s_stmt)

到此: salt_query = curs.execute(s_stmt) salt = curs.fetchone()[0]

最后一行从表中获取结果,并获取第一列的值。该值将是一个字符串而不是SQLite游标。