开发者

Testing a session variable

开发者 https://www.devze.com 2023-03-04 14:35 出处:网络
I came across Django request.session; I know how to set and test it for a specific value. request.session[\'name\'] = "dummy"

I came across Django request.session; I know how to set and test it for a specific value.

request.session['name'] = "dummy"

and somewhere I check

if request.session['name'] 开发者_运维技巧== "dummy" :
   #do something

But, now I have to check whether the session variable was even set in the first place? I mean how can I check whether there exists a value in the request.session['name'] is set?

Is there a way to check it?


Treat it as a Python dictionary:

if 'name' in request.session:
    print request.session['name']

How to use sessions: Django documentation: How to use sessions


get will do all the work for you. Check if the key exists, if not then the value is None

if request.session.get('name', None) == "dummy":
    print 'name is = dummy'


Another way of doing this is put it in try.

In this the third example code snippet

if you apply del operation in a session variable it which does not exist, so it throws KeyError.

so check it like this.

try:
    print(request.session['name'])
except KeyError:
    print('name variable is not set')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号