How do I clear a flask session? How do I clear a flask session? flask flask

How do I clear a flask session?


from flask import sessionsession.clear()

I use session like this with flask, it does work.I don't use SecureCookieSession though, but maybe it can help.


You can also iterate through the session and call session.pop() for each key in your session. Pop will remove the variable from the session and you don't have to keep updating your secret key.

for key in list(session.keys()):     session.pop(key)


As pointed out in Jerry Unkhaptay's answer, as well as in corresponding Flask documentation section, you can simply do:

from flask import sessionsession.clear()

Though, as, fairly, pointed out in comment, by alejandro:

If you are also using flashed messages in your application, you should consider that flashed messages are stored in the session and can, therefore, be erased before they are flashed if you clear the session.

My suggestion is to take advantage of list comprehension:

[session.pop(key) for key in list(session.keys())]

it is essentially the same for loop as in TheF1rstPancake's answer, though a one-liner. We can remove everything, except flashed messages, from session (or add add any other conditions, for that matter) quite easily, like so:

[session.pop(key) for key in list(session.keys()) if key != '_flashes']