You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Flask+MySQL实现登录时账号密码正确却报错的问题

问题排查与修复方案

1. 用户存在性判断逻辑错误

fetchone() 查询无匹配用户时返回 None,而非空列表,原代码中 if len(users) > 0 会触发 TypeError,导致后续校验逻辑无法正常执行。应直接判断用户对象是否存在:

if users:  # 替换原有的 if len(users) > 0:

2. BCrypt 密码校验写法错误

原代码用 bcrypt.hashpw 重新哈希后对比的方式冗余且易出编码问题,BCrypt 提供了更可靠的 checkpw 方法直接完成校验:

# 替换原有的密码校验判断
if bcrypt.checkpw(Password, users["Password"].encode('utf-8')):

注意:如果注册时存储的是解码后的字符串哈希(比如注册时用了 .decode('utf-8')),这里的 users["Password"].encode('utf-8') 是正确的;如果注册时直接存储字节串,需确保数据库字段支持二进制存储,此时直接用 users["Password"] 即可。

3. 调试建议(可选)

可以临时添加打印语句,确认查询到的哈希值与输入密码的编码状态,方便快速定位问题:

if users:
    print("数据库存储的密码哈希:", users["Password"])
    print("输入密码编码后:", Password)
    # 后续校验逻辑

修复后的完整代码

@app.route('/login', methods=["GET", "POST"])
def login():
    if request.method == 'POST':
        Email = request.form['Email']
        Password = request.form['Password'].encode('utf-8')
        
        curl = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        curl.execute("SELECT * FROM user WHERE Email=%s",(Email,))
        users = curl.fetchone()
        curl.close()
        
        if users:
            if bcrypt.checkpw(Password, users["Password"].encode('utf-8')):
                session['First_name']= users['First_name']
                session['Last_name']= users['Last_name']
                session['Email'] = users['Email']
                return render_template("index.html")
            else:
                return "Incorrect username or password"
        else:
            return "Error user not found"
    else:
        return render_template("login.html")

内容的提问来源于stack exchange,提问作者Stephanie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:05:25