doniyor
doniyor

Reputation: 37866

django session check for existance

I am trying to check if the session does have anything in it. What I did is:

if request.session: 
   # do something

but it is not working. Is there any way of knowing whether the session contains something at that moment?

If I do request.session['some_name'], it works, but in some cases, I just need to know if the session is empty or not.

Asking with some specific names is not always a wanted thing. Eg. if there is no session, it returns an error, since some_name doesn't exist.

Upvotes: 2

Views: 7281

Answers (2)

droidballoon
droidballoon

Reputation: 730

Nowadays there's a convenience method on the session object

request.session.is_empty()

Upvotes: 1

freakish
freakish

Reputation: 56467

request.session is an instance of SessionBase object which behaves like dictionary but it it is not a dictionary. This object has a "private" field ( actually it's a property ) called _session which is a dictionary which holds all data.

The reason for that is that Django does not load session until you call request.session[key]. It is lazily instantiated.

So you can try doing that:

if request.session._session:
    # do something

or you can do it by looking at keys like this:

if request.session.keys():
    # do something

Note how .keys() works:

django/contrib/sessions/backends/base.py

class SessionBase(object):
    # some code

    def keys(self):
        return self._session.keys()

    # some code

I always recommend reading the source code directly.

Upvotes: 7

Related Questions