python 在 Django 中测试 cookie 的存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1466732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:20:09  来源:igfitidea点击:

Testing for cookie existence in Django

pythondjangohttpcookies

提问by M. Ryan

Simple stuff here...

简单的东西在这里...

if I try to reference a cookie in Django via

如果我尝试通过以下方式在 Django 中引用 cookie

request.COOKIE["key"]

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

如果 cookie 不存在,则会抛出一个关键错误。

For Django's GETand POST, since they are QueryDictobjects, I can just do

对于 Django 的GETand POST,因为它们是QueryDict对象,我可以做

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...

对于不是 Try/Catch 块的 cookie,最接近的是什么?

回答by Daniel Roseman

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

request.COOKIES是一个标准的 Python 字典,所以同样的语法也有效。

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'.

如果键存在,则返回值,否则返回 'default' - 你可以用你喜欢的任何东西代替 'default'。

回答by kender

First, it's

首先,它是

request.COOKIES

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

不是request.COOKIE。另一个会给你一个错误。

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:

会给你你需要的。如果要获取cookie的值,可以使用:

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

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

然后,如果没有 key "key",您将得到一个None而不是异常。