Search code examples
pythondjangosessiondictionarykeyerror

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.

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.


Solution

  • Interesting. A quick test revealed a KeyError on the del item line and not down where you say it would happen. 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.