[Answered ]-Request.session.clear() vs request.session.flush() in Django

1👍

The documentation is indeed very unclear on this point, it is quite remarkable that these methods are not documented.

When we look at the source code however, then we see that .flush() does more than .clear(). Indeed if we look at the source code [GitHub]:

def flush(self):
    """
    Remove the current session data from the database and regenerate the
    key.
    """
    self.clear()
    self.delete()
    self._session_key = None

.flush() [Django-doc] does more, it also deletes the sessions record (that is not the case for .clear() which "empties" the dictionary, but the record still exists), and sets the ._session_key to None so it will regenerate a new session key.

.clear() [Django-doc] on the other hand only removes the items attached to this session. This thus means that the session key remains the same, that the Session record is not removed (but will then only have an empty dictionary as data).

But both will indeed basically "log out" the user, since the session normally stores the user id of the logged in user, and thus in the next request, it will use the same session, but can no longer link it to any data, hence there is no user linked to the request.

Leave a comment