一尘不染

如何使用Flask检索会话数据?

flask

我有flask + wtforms应用程序。我可以在login()用户对象中看到存储为

  if user:
   if user.verify_password(form.password.data):
    flash('You have been logged in')
    user.logins += 1

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

    session['user'] = user

现在我想找回用户

if 'user' in session:
       User=session.get('user')
       print User.nickname ###<< how to retrieve specific object member?

它失败,并显示以下消息:

Instance <User at 0x8e5a64c> is not bound to a Session; attribute refresh operation cannot proceed

阅读 424

收藏
2020-04-08

共1个答案

一尘不染

这很简单。如果要检索特定对象,只需在会话内添加变量的名称,例如session['nickname']

你可以通过执行相同的方式设置变量session['nickname'] = nickname。

在你的情况下,你可以将其更改为以下内容

if 'user' in session:
    user = session['user']
    print user

if 'nickname' in session:
    nickname = session['nickname']
    print nickname

这是我用于登录的功能的简化版本。

@app.route('/login', methods=['POST'])
def login():
    """Authenticate User"""
    username = request.form['username'].strip()
    nickname = request.form['nickname'].strip()
    password = request.form['password']
    try:
        if Auth().VerifyLogin(username, password):
            session['username'] = username
            session['nickname'] = nickname
        else:
            # failed to login, do something.
    except Exception as why:
        app.logger.critical('.....')
2020-04-08