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...
Django provides built-in methods to set and fetch cookie. The set_cookie() method is used to set a cookie and get() method is used to get the cookie. The request. COOKIES['key'] array can also be used to get cookie values.
Django uses a cookie containing a special session id to identify each browser and its associated session with the site. The actual session data is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users).
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'.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With