在 Django Session 中修改字典不会修改 Session [英] Modifying Dictionary in Django Session Does Not Modify Session

查看:46
本文介绍了在 Django Session 中修改字典不会修改 Session的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的会话中存储字典,由字符串键引用:

<预><代码>>>>request.session['my_dict'] = {'a': 1, 'b': 2, 'c': 3}

我遇到的问题是我直接修改字典的时候,下次请求的时候不会改变值:

<预><代码>>>>request.session['my_dict'].pop('c')3>>>request.session.has_key('c')错误的#看起来还行......# 下一个请求>>>request.session.has_key('c')真的# 是什么赋予了!

解决方案

作为 文档说明,另一种选择是使用

SESSION_SAVE_EVERY_REQUEST=True

无论如何都会使每个请求都发生这种情况.如果这种情况在您的代码中经常发生,可能是值得的;我猜偶尔的额外开销不会太多,而且远远少于忽略包含

的潜在问题

request.session.modified = True

每次都要排队.

I am storing dictionaries in my session referenced by a string key:

>>> request.session['my_dict'] = {'a': 1, 'b': 2, 'c': 3}

The problem I encountered was that when I modified the dictionary directly, the value would not be changed during the next request:

>>> request.session['my_dict'].pop('c')
3
>>> request.session.has_key('c')
False
# looks okay...
...
# Next request
>>> request.session.has_key('c')
True
# what gives!

解决方案

As the documentation states, another option is to use

SESSION_SAVE_EVERY_REQUEST=True

which will make this happen every request anyway. Might be worth it if this happens a lot in your code; I'm guessing the occasional additional overhead wouldn't be much and it is far less than the potential problems from neglecting from including the

request.session.modified = True

line each time.

这篇关于在 Django Session 中修改字典不会修改 Session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆