sqlalchemy.exc.InvalidRequestError:对象'<user at =“” 0x10d437eb8 =“”>'已附加到会话'2'(这是'3')

时间:2019-03-13 14:39:49

标签: flask sqlalchemy

每次登录一个新帐户并登录时,我都在创建一个页面来重置密码,当我尝试重置密码时,会显示sqlalchemy.exc.InvalidRequestError: Object '<User at 0x10d437eb8>' is already attached to session '2' (this is '3'),每次修改一行数据库中已经存在该错误。

这是我的代码:

注册视图:

def register():
    form = RegisterForm()
    if form.validate_on_submit():
        data = form.data
        user = User(
            name=data["name"],
            email=data["email"],
            pwd=generate_password_hash(data["pwd"]),
            avatar="user-blue.png",
            uuid=uuid.uuid4().hex
        )
        db.session.add(user)
        db.session.commit()
        return redirect(url_for("home.login"))
    return render_template("home/register.html", form=form)

重置密码视图:

def pwd_reset():
    form = PwdForm()
    if form.validate_on_submit():
        data = form.data
        user = User.query.filter_by(name=session["user"]).first()
        from werkzeug.security import generate_password_hash
        user.pwd = generate_password_hash(data["new_pwd"])
        db.session.add(user) # problem here
        db.session.commit()
        return redirect(url_for("home.success"))
    return render_template("home/pwd_reset.html", form=form)

据我所知,我不能在现有行上使用db.session.add吗?如何解决这个问题

1 个答案:

答案 0 :(得分:1)

您不需要将user添加到数据库会话。

只需修改预期的字段并提交会话:

def pwd_reset():
    form = PwdForm()
    if form.validate_on_submit():
        data = form.data
        user = User.query.filter_by(name=session["user"]).first()
        from werkzeug.security import generate_password_hash
        user.pwd = generate_password_hash(data["new_pwd"])
        db.session.commit()
        return redirect(url_for("home.success"))
    return render_template("home/pwd_reset.html", form=form)