我如何使用Django会话来读取/设置cookie?

时间:2022-06-03 20:27:16

I am trying to use the Django sessions to read and set my cookies, but when i do the following the program just does not respond!

我正在尝试使用Django会话来读取和设置我的cookie,但是当我执行以下操作时,该程序只是没有响应!

sessionID = request.session["userid"]

sessionID = request.session [“userid”]

The program does not pass this point!

该计划没有通过这一点!

Any ideas?

1 个解决方案

#1


First, Django already creates a user object for you so you don't need to store it in the session. Just access it as:

首先,Django已经为您创建了一个用户对象,因此您无需将其存储在会话中。只需访问它:

request.user

For example, to get the username you would use:

例如,要获取您将使用的用户名:

request.user.username

Next, if you want to store information in the session you don't need to worry about it at the cookie level. Simply write key / value pairs to the request.session dictionary.

接下来,如果要在会话中存储信息,则无需在cookie级别担心。只需将键/值对写入request.session字典即可。

Here are some examples from the Django documentation.

以下是Django文档中的一些示例。

Edit: The reason your program isn't responding is because a KeyError exception is being raised. 'userid' doesn't exist as a key in the session dictionary (unless you have added it yourself).

编辑:程序没有响应的原因是因为引发了KeyError异常。 'userid'不作为会话字典中的键存在(除非您自己添加了它)。

This is why it is better to program dictionary reads like this:

这就是为什么编写这样的字典读取更好的原因:

id = request.session.get('somekey', False)

Which will return False if 'somekey' doesn't exist in the dictionary.

如果字典中不存在'somekey',则返回False。

#1


First, Django already creates a user object for you so you don't need to store it in the session. Just access it as:

首先,Django已经为您创建了一个用户对象,因此您无需将其存储在会话中。只需访问它:

request.user

For example, to get the username you would use:

例如,要获取您将使用的用户名:

request.user.username

Next, if you want to store information in the session you don't need to worry about it at the cookie level. Simply write key / value pairs to the request.session dictionary.

接下来,如果要在会话中存储信息,则无需在cookie级别担心。只需将键/值对写入request.session字典即可。

Here are some examples from the Django documentation.

以下是Django文档中的一些示例。

Edit: The reason your program isn't responding is because a KeyError exception is being raised. 'userid' doesn't exist as a key in the session dictionary (unless you have added it yourself).

编辑:程序没有响应的原因是因为引发了KeyError异常。 'userid'不作为会话字典中的键存在(除非您自己添加了它)。

This is why it is better to program dictionary reads like this:

这就是为什么编写这样的字典读取更好的原因:

id = request.session.get('somekey', False)

Which will return False if 'somekey' doesn't exist in the dictionary.

如果字典中不存在'somekey',则返回False。