Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Session Key is set

I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving an error. Is there any way to check if a session is set, so that it can be set if it doesn't exist?

like image 835
Julio Avatar asked Oct 11 '10 18:10

Julio


People also ask

How do you check if session is set or not?

You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable. For example: <?

How do you check session is set or not in Java?

Use request. getSession(false) to check if a user has a session. With this method you don't create a new session if you're going to render a view based on if a user is authenticated or not.

How can I see sessions in Django?

If you want to use a database-backed session, you need to add 'django. contrib. sessions' to your INSTALLED_APPS setting. Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.

Which of the following is used to check if session variable is already set or not in PHP?

Make use of isset() function to check if session variable is already set or not.


2 Answers

I assume that you want to check if a key is set in session, not if a session is set (don't know what the latter means). If so:

You can do:

if key not in request.session:
    # Set it.

In your case:

if 'cart' not in request.session:
    # Set it.

EDIT: changed the code snippet to use key not in rather than not key in. Thanks @katrielalex.

like image 175
Manoj Govindan Avatar answered Oct 04 '22 10:10

Manoj Govindan


You can use the get-method on the session dictionary, it will not throw an error if the key doesn't exist, but return none as a default value or your custom default value:

cart = request.session.get('cart')
cart = request.session.get('cart', 'no cart')
like image 29
Bernhard Vallant Avatar answered Oct 04 '22 09:10

Bernhard Vallant