Python 烧瓶中的当前用户更改值

Python 烧瓶中的当前用户更改值,python,flask,Python,Flask,我是新来的烧瓶,所以请原谅我,如果我的代码是糟糕的,并尝试给予更正。 我正在尝试在我的应用程序中使用flask登录实现登录。当我登录时,当前用户显示为,但刷新后显示为匿名 下面是我认为在我的视图文件中的相关代码 @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.fi

我是新来的烧瓶,所以请原谅我,如果我的代码是糟糕的,并尝试给予更正。 我正在尝试在我的应用程序中使用flask登录实现登录。当我登录时,
当前用户
显示为
,但刷新后显示为匿名

下面是我认为在我的视图文件中的相关代码

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if form.validate_on_submit():       
            if user is None:
                user = User(name=form.name.data,email=form.email.data,password=form.password.data) 
                db.session.add(user)
                db.session.commit()
                login_user(user,remember=True)
                return redirect(url_for('index'))
            else:
                user=User(name=form.name.data,password=form.password.data,email=form.email.data)
                if True #eventually this will check whether the password you inputted matches the password associated with the email you inputted:
                    login_user(user,remember=True)
    return render_template('login.html', form=form,)

@app.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(url_for("index"))

@app.before_request
def before_request():
    g.user = current_user 
我已经很好地搜索了答案,所以我认为问题在于我的登录用户系统,而不是当前用户。 提前谢谢

编辑:
问题是,我的
get\u id
函数返回的是
self.id
,该函数不存在。我让它返回了self.email,一切正常。

我注意到,如果找不到现有用户,您将创建一个用户对象,但没有调用以下命令将其添加到数据库中:

db.session.add(user)
db.session.commit()
这可以解释为什么在页面刷新时,您会丢失有关用户的信息


另外,您正在检查
if form.validate\u on_submit():
两次,但这只需要检查一次。

@matthealey您的意思是在if user is None的else子句中吗?如果我把它放进去,我会收到一个错误,因为电子邮件在我的数据库中必须是唯一的。我是否应该先删除该用户,然后每次都再次添加它们?是的,您可能必须这样做。此时,您正在生成一个用户对象并登录该用户,但没有将该用户保存到数据库,因此在下一次页面加载时,您将丢失该用户。我如何删除该用户?我不确定,这取决于您使用的数据库。或者,您可以实现代码来实际检查用户的密码是否正确。现在,我建议您删除在“else”语句之后创建用户对象的那一行。当您已经从初始查询中获得了用户对象时,不需要创建它。