我有一个基于 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/