简体   繁体   English

尝试替换时的Django会话字典KeyError

[英]Django session dictionary KeyError when attempting to replace

I am dealing with a third-party authorization issue on the backend and encountering strange session store behavior. 我正在处理后端的第三方授权问题,并遇到奇怪的会话存储行为。

When I detect that the third part session authorization has become invalid, I re-authenticate and I am attempting to update the data in the session, which is not working. 当我检测到第三方会话授权已变得无效时,我将重新进行身份验证,并尝试更新会话中的数据,该数据无法正常工作。

The problem is that after I delete the key from the session, I get a KeyError when I try to replace it once I have the updated information. 问题是,当我从会话中删除密钥后,一旦获得更新的信息,尝试替换它时,我会收到一个KeyError。

def my_session_thing(invalidate=False):
    if invalidate:
        del self.request.session['my_session_dict']
        self.request.session.modified = True

    my_session_dict = self.request.session.get('my_session_dict')
    if my_session_dict is not None:
        self.current_session_dict = my_session_dict
        return

    my_new_session_dict = {
        'foo': 'bar'
    }

    # ** Why does this raise a KeyError when invalidate is True? **
    self.request.session['my_session_dict'] = my_new_session_dict

I am currently exploring alternatives to this strategy, but I found this behavior contradicts the dictionary-like behavior that the "How to use sessions" documentation describes, so it would be worth posting. 我目前正在探索此策略的替代方法,但是我发现此行为与“如何使用会话”文档中描述的类似字典的行为相矛盾,因此值得一提。

Interesting. 有趣。 A quick test revealed a KeyError on the del item line and not down where you say it would happen. 快速测试显示了del item行上的KeyError,而不是您所说的可能发生的地方。 Apparently you have to check for the key's existence first, before you can delete it: 显然,您必须先检查密钥的存在,然后才能删除它:

def my_session_thing(invalidate=False):
    if invalidate and 'my_session_dict' in self.request.session:

As to why exactly this is necessary when it shouldn't be, I cannot tell (I smell property shenanigans). 至于到底为什么不应该这样做,我不知道(我闻到了地产恶作剧)。 Seems like the session does not load its storage when calling __del__ or pop . 似乎在调用__del__pop时会话未加载其存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM