Django会话变量重置

3

我有一个基于cookie的会话,并尝试将两个页面之间的数据存储在会话中,但是存储在会话变量中的数据一直在重置。

一个例子是:

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

我在想,为什么会出现这种情况?

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

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

...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接