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

Flask注册提交POST请求后跳转GET、不执行数据库插入逻辑是什么原因

问题原因及修复方案

核心问题1:SQLite查询参数格式错误

sqlite3的execute()方法要求传入的SQL参数必须是元组或列表类型,你的代码中直接传入单个字符串username作为参数,会触发参数类型错误。

# 错误写法
check = con.execute("SELECT * FROM users WHERE username = ?", username)
# 正确写法,单元素元组需要加末尾逗号
check = con.execute("SELECT * FROM users WHERE username = ?", (username,))

核心问题2:空查询结果判断逻辑错误

当要注册的用户名不存在时,check.fetchone()会返回None,你的代码后续直接调用len(checked)会触发TypeError,直接进入没有任何日志输出的空except块,执行回滚后跳出try逻辑,最终返回注册页,这就是日志仅输出到「Checked username successfully」就结束的原因。
判断用户名是否存在无需调用len,直接判断值是否为None即可:

# 错误写法
if len(checked) != 0:
# 正确写法
if checked is not None:

其他优化建议

你当前使用的裸except会捕获所有异常但不打印错误信息,极不利于问题排查,建议修改为捕获具体异常,或者至少打印异常信息;同时Flask的redirect方法不支持直接传递message参数,提示信息可以通过session、查询参数或者render_template传入模板。

修正后的完整后端代码

@app.route("/register", methods=["GET", "POST"])
def register():
    message = ""
    if request.method == "POST":
        con = None
        try:
            username = request.form["username"]
            password = request.form["password"]
            confirmation = request.form["confirmation"]
            # 检查用户名是否已存在
            with sqlite3.connect("flashcards.db") as con:
                # 修正参数格式为元组
                check = con.execute("SELECT * FROM users WHERE username = ?", (username,))
                checked = check.fetchone()
                print(checked) 
                print(bcolors.OK + "Checked username successfully" + bcolors.RESET)
                
                # 修正空结果判断逻辑
                if checked is not None:
                    print(bcolors.OK + "if checked is not None" + bcolors.RESET)
                    message = "该用户名已被占用"
                    return render_template("register.html", message=message)

                if password == confirmation and username.strip():
                    print(bcolors.OK + "if password == confirmation and username" + bcolors.RESET)
                    insert_query = "INSERT INTO users (username, hashed_password) VALUES(?, ?)"
                    values = (username, generate_password_hash(password, method="pbkdf2:sha256", salt_length=8))
                    cur = con.cursor()
                    cur.execute(insert_query, values)
                    con.commit()
                    print(bcolors.OK + "Data inserted successfully" + bcolors.RESET)
                    return redirect("/login")
                else:
                    print(bcolors.OK + "In the else" + bcolors.RESET)
                    message = "两次输入的密码不一致或用户名为空"
                    return render_template("register.html", message=message)
        except Exception as e:
            print(f"注册异常:{e}")
            if con:
                con.rollback()

    return render_template("register.html", message=message)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 04:18:03