簡體   English   中英

燒瓶中的current_user更改值

[英]current_user changing value in flask

我是不熟悉燒瓶的人,所以如果我的代碼不好,請原諒我,並嘗試進行更正。 我正在嘗試在我的應用程序中使用flask-login實現登錄。 當我登錄時, current_user顯示為<user "nickname"> ,但刷新后顯示為匿名。

我認為這是我的視圖文件中的相關代碼。

@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 

我一直在尋找答案,所以我認為問題出在我的用戶登錄系統上,而不是current_user 提前致謝

編輯:問題原來是我的get_id函數返回的self.id ,不存在。 我讓它返回self.email ,一切都很好。

我注意到,如果找不到現有用戶,那么您正在創建一個用戶對象,但沒有調用以下命令將它們添加到數據庫中:

db.session.add(user)
db.session.commit()

這可以解釋為什么在頁面刷新時丟失有關用戶的信息。

另外,您還要檢查if form.validate_on_submit():兩次,但這只需要檢查一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM