3

I have a cookie based session in place and I tried to keep data between two pages stored in the session however the data stored in the session variable keeps restting.

An example of this was:

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 []

I was wondering why this is the case?

4

1 回答 1

7

request.session['foo'].append('bar')不影响会话。仅request.session['...'] = .../del request.session['...']影响会话。

试试下面的代码。

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

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

默认情况下,Django 仅在会话被修改时才保存到会话数据库中——也就是说,如果它的任何字典值已被分配或删除:

# 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'

在上面示例的最后一种情况下,我们可以通过在会话对象上设置 modified 属性来明确告诉会话对象它已被修改:

request.session.modified = True

...

于 2013-06-26T06:14:38.940 回答