How to retrieve session data with Flask?

前端 未结 1 2098
無奈伤痛
無奈伤痛 2021-02-19 12:33

I have flask+wtforms application. I can see in login() user object stored as

  if user:
   if user.verify_password(form.password.data):
    flash(\'You have be         


        
相关标签:
1条回答
  • 2021-02-19 13:03

    It's simple. If you want to retrieve a specific object simply add the name of the variable within session, e.g. session['nickname'].

    You can set the variable the same way, by doing 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('.....')
    
    0 讨论(0)
提交回复
热议问题