views:

213

answers:

2

Simple stuff here...

if I try to reference a cookie in Django via

request.COOKIE["key"]

if the cookie doesn't exist that will throw a key error.

For Django's GET and POST, since they are QueryDict objects, I can just do

if "foo" in request.GET

which is wonderfully sophisticated...

what's the closest thing to this for cookies that isn't a Try/Catch block, if anything...

A: 

First, it's

request.COOKIES

not request.COOKIE. Other one will throw you an error.

Second, it's a dictionary (or, dictionary-like) object, so:

if "foo" in request.COOKIES.keys()

will give you what you need. If you want to get the value of the cookie, you can use:

request.COOKIES.get("key", None")

then, if there's no key "key", you'll get a None instead of an exception.

kender
Since python 2.2, you can use 'if "foo" in request.COOKIES' -- there's no need to add '.keys()'
Ian Clelland
right. Probably it's just me, but I like the longer version more (maybe a matter of working with pre-2.2 for a long time). It's more symmetrical and so more implicit what do I check if I use: in "foo" in dict.keys() and if "bar" in dict.values()...
kender
+4  A: 

request.COOKIES is a standard Python dictionary, so the same syntax works.

Another way of doing it is:

request.COOKIES.get('key', 'default')

which returns the value if the key exists, otherwise 'default' - you can put anything you like in place of 'default'.

Daniel Roseman