简体   繁体   English

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

[英]How do i use Django session to read/set cookies?

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? 有任何想法吗?

First, Django already creates a user object for you so you don't need to store it in the session. 首先,Django已经为您创建了一个用户对象,因此您无需将其存储在会话中。 Just access it as: 只需访问它:

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. 接下来,如果要在会话中存储信息,则无需在cookie级别担心。 Simply write key / value pairs to the request.session dictionary. 只需将键/值对写入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. 编辑 :程序没有响应的原因是因为引发了KeyError异常。 'userid' doesn't exist as a key in the session dictionary (unless you have added it yourself). '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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM