Django: Session Cache not updated when using Cookie Based Session Storage

最后都变了- 提交于 2019-12-06 12:38:39

问题


I am trying to use Django Session to cache some data. I don't have a database in my web app so, I am using the cookie-based storage mechanism. I am able to successfully save the data in the session only for the first time. Henceforth, if I try to update the session cache it doesn't work. Here is what I had found:

prior_states = request.session.get(workflow_id, [])
print "prior_state >>> ", prior_states
if state_id in prior_states:
    request.session.update({workflow_id: prior_states[:prior_states.index(state_id) + 1]})
else:
     prior_states.append(state_id)
     request.session.update({workflow_id : prior_states})

Test Code

#1st request:
print request.session.get(1) --> None
request.session[1] = [101] --> works
print request.session.get(1) --> [101]
#2nd request:
print request.session.get(1) --> [101]
request.session[1] = [101, 102] --> works
print request.session.get(1) --> [101,102]

#3rd request:
print request.session.get(1) --> [101] --> Can't follow why?

Thanks in advance!


回答1:


According to the Django Documentation:

https://docs.djangoproject.com/en/1.6/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

request.session.modified = True

To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST setting to True. When set to True, Django will save the session to the database on every single request.

Note that the session cookie is only sent when a session has been created or modified. If SESSION_SAVE_EVERY_REQUEST is True, the session cookie will be sent on every request.

Similarly, the expires part of a session cookie is updated each time the session cookie is sent.



来源:https://stackoverflow.com/questions/24147600/django-session-cache-not-updated-when-using-cookie-based-session-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!