python - Django session 变量重置

标签 python django session-variables session-cookies

我有一个基于 cookie 的 session ,我试图将两个页面之间的数据保存在 session 中,但是存储在 session 变量中的数据一直处于静止状态。

这方面的一个例子是:

At Home page:
request.session['foo'] = []
request.session['foo'].append('bar')
print request.session['foo'] will yield ['bar']

On second page:
print request.session['foo'] will yield []

我想知道为什么会这样?

最佳答案

request.session['foo'].append('bar') 不影响 session 。只有 request.session['...'] = .../del request.session['...'] 影响 session 。

尝试以下代码。

request.session['foo'] = ['bar']

https://docs.djangoproject.com/en/dev/topics/http/sessions/#when-sessions-are-saved

By default, Django only saves to the session database when the session has been modified – that is if any of its dictionary values have been assigned or deleted:

# Session is modified.
request.session['foo'] = 'bar'

# Session is modified.
del request.session['foo']

# Session is modified.
request.session['foo'] = {}

# Gotcha: Session is NOT modified, because this alters
# request.session['foo'] instead of request.session.
request.session['foo']['bar'] = 'baz'

In the last case of the above example, we can tell the session object explicitly that it has been modified by setting the modified attribute on the session object:

request.session.modified = True

...

关于python - Django session 变量重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17312688/

相关文章:

Python 正则表达式仅检查子字符串是否后跟子字符串

python - 为不同视频的视频帧创建新目录时出错

python - 正确完成管道中的多处理

python - 在 Django 中如何安排每日报告以电子邮件形式发送

php - Cookie 与基于 Session 的 flash 消息

python - 尝试升级 pyarrow 会导致错误

python - django-debug-toolbar 安装导致 : No such file or directory: '/var/www/static'

.net - 调试 ASP.NET session 变量

c# - 如何创建动态数组

python - 做 Django 导入的正确方法是什么?