Python 检查 Django 中是否设置了会话密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3908761/
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-08-18 13:18:15  来源:igfitidea点击:

Check if Session Key is Set in Django

pythondjango

提问by Julio

I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving an error. Is there anyway to check if a session is set, so that it can be set if it doesn't exist?

我正在尝试在 Django 中创建一个相对简单的购物车。我将购物车存储在 request.session['cart'] 中。因此,当向其中添加任何内容时,我需要访问此会话中的数据。但是,如果会话尚未设置,我将无法访问它而不会收到错误消息。无论如何要检查是否设置了会话,以便在它不存在时可以设置它?

采纳答案by Manoj Govindan

I assume that you want to check if a keyis set in session, not if a sessionis set (don't know what the latter means). If so:

我假设您想检查是否在会话中设置了密钥,而不是是否设置了会话(不知道后者是什么意思)。如果是这样的话:

You can do:

你可以做:

if key not in request.session:
    # Set it.

In your case:

在你的情况下:

if 'cart' not in request.session:
    # Set it.

EDIT: changed the code snippet to use key not inrather than not key in. Thanks @katrielalex.

编辑:将代码片段更改为 usekey not in而不是not key in. 谢谢@katrielalex。

回答by Bernhard Vallant

You can use the get-method on the session dictionary, it will not throw an error if the key doesn't exist, but return none as a default value or your custom default value:

您可以get在会话字典上使用-method,如果键不存在,它不会抛出错误,但返回 none 作为默认值或您的自定义默认值:

cart = request.session.get('cart')
cart = request.session.get('cart', 'no cart')