Question

I am trying to clear all of the session variables but not logout the current user.

user = request.session.get('member_id', None)
request.session.flush()
request.session.modified = True
request.session['member_id'] = user
request.session.modified = True

Will this also affect other users of the site?

Was it helpful?

Solution

As of Django 1.8, any call to flush() will log out the user. From the docs:

Changed in Django 1.8: Deletion of the session cookie is a behavior new in Django 1.8. Previously, the behavior was to regenerate the session key value that was sent back to the user in the cookie.

If you want to be able to delete keys but keep the user logged in, you'll need to handle it manually:

for key in request.session.keys():
    del request.session[key]

Or just delete the specific keys that are of concern:

del request.session['mykey']

OTHER TIPS

In versions of django < 1.8, session.flush deletes the session data and regenerates the session key. It won't affect other users since session keys are unique.

As an improvement to shacker's1 in Python 2.x dict.keys() returns a list copy of the keys of a dictionary, in Python 3.x it instead returns an iterator. changing the size of an iterator is unwise. For an version safe implementation casting to list will prevent any size issues

for key in list(request.session.keys()):
    del request.session[key]

My previous answer suggested the use of dict.viewkeys() but it will also return an iterator in python 3.x.

You can clear keys you have set in the django session, but to do so without logging the user out takes a little bit of trickiness; request.session.flush() logs the user out. And request.session = {} in deleting all keys in the session dictionary will also log the user out.

Thus, to clear out keys without logging the user out, you have to avoid keys that begin with an underscore character. The following code does the trick:

for key in list(request.session.keys()):
  if not key.startswith("_"): # skip keys set by the django system
    del request.session[key]

request.session internally uses cookies. And when a user requests some url of the site, only cookies present on that user's machine is sent to the server. So, request.session is always tied to the current user.

So, this in no way will affect other users of the site.

Also this will not log out the current user, because you are using flush() which will delete the old session and create a new session and this new session would be associated with the current user.

flush() internally uses clear(), delete() and create().

In the response this new session's key would be sent as a cookie and in subsequent requests this new session would continue working normally.

session_keys = list(request.session.keys())
    for key in session_keys:
        del request.session[key]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top