How to determine if a variable exists in a Flask session?

I would like to know if the session key ['logged_in'] exists, which means that my user has already logged in.

Example:

if (session['logged_in'] != None): if session['logged_in'] == True: return redirect(url_for('hello')) 

However, if the key "logged_in" does not exist, it therefore generates an error. Since the session object is like a dictionary, I thought I could use the has_key () method, but that also does not work. Is there an easy way to determine if a session contains data without generating an error?

+6
source share
4 answers

In general, accessing session elements is as simple as using a dictionary.

You can use has_key() (there was no had_key() method), but it is better to use in or get() . An example flash application that accesses session elements:

 from flask import Flask, session, request, redirect, url_for app = Flask(__name__) @app.route('/') def index(): if session.get('logged_in') == True: return 'You are logged in' return 'You are not logged in' @app.route('/login') def login(): session['logged_in'] = True return redirect(url_for('index')) @app.route('/logout') def logout(): session.pop('logged_in', None) return redirect(url_for('index')) if __name__ == '__main__': app.secret_key = 'ssssshhhhh' app.run() 
+5
source

You can use something like this to check if a key exists in a dict session:

 if session.get('logged_in'): if session['logged_in'] == True: return redirect(url_for('hello')) 
+3
source

As @rnevius mentioned , if the main problem you are trying to solve is testing to see if the current user is logged in, then it may be useful for you to use some of the built-in Flask function .

If you are just trying to find out if a certain key ( logged_in ) exists in the session object, you can treat the session object as if it were a dictionary, and simply use the following syntax:

 if session.get('logged_in') is not None: # Here we know that a logged_in key is present in the session object. # Now we can safely check it value if session['logged_in'] == True: return redirect(url_for('hello')) 
+1
source
 if session.get('logged_in') is not None: # do something for logged in user return render_template('success.html') else: # do something for non-logged in user return render_template('index.html') 

Give it a try, it should work.

Sorry for the late reply, but I fought for the same things, and this is the main formula.

In my scenario, I have a users table in the mysql database, with which, when a user logs in or creates an account, a session variable is created and the id set by that user.

If this user now goes to the root ('/') , the session variable is detected and success.html served.

If no value is found for session['logged_in'] than index.html , where they can create an account or log in.

+1
source

Source: https://habr.com/ru/post/983498/


All Articles