简体   繁体   English

如何用Flask取回session的数据?

[英]How to retrieve session data with Flask?

I have flask+wtforms application.我有 flask+wtforms 应用程序。 I can see in login() user object stored as我可以在 login() 中看到用户 object 存储为

  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

Now I wanted to retrieve the user现在我想检索用户

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

It fails with message like:它失败并显示如下消息:

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

It's simple.这很简单。 If you want to retrieve a specific object simply add the name of the variable within session, eg session['nickname'] .如果您想检索特定对象,只需在会话中添加变量的名称,例如session['nickname']

You can set the variable the same way, by doing session['nickname'] = nickname .您可以通过执行session['nickname'] = nickname以相同的方式设置变量。

In your case you would change it to the following在您的情况下,您可以将其更改为以下内容

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

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

This is an simplified version of the function I use for login.这是我用于登录的函数的简化版本。

@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('.....')

To see all that is in your session you can print(session) .要查看 session 中的所有内容,您可以print(session) You should get a response like你应该得到这样的回应

<SecureCookieSession {'_flashes': [('info', 'Duplication is not allowed ')], 'el1-s': 'Physics', 'el1grade-s': 'B2', 'el2-s': 'E-Maths', 'el2grade-s': 'A1', 'english-s': 'A1', 'mathematics-s': 'A1', 'science-s': 'A1', 'social-s': None}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM