7

I've seen many examples and questions about clearing a Flask session, but haven't been able to find a clear answer on how to only clear a specific key or set of keys.

If I don't want to clear the entire session, how can I can completely remove (as if it never existed) a specific key?

For example, I want to clear session['foo'], but keep session['bar']. So when I later do:

if 'foo' in session: 

This should return False.

2 Answers 2

11

from session.keys() have you tried popping out keys?

# remove the keyname from the session if it is there session.pop('key_name') 
Sign up to request clarification or add additional context in comments.

5 Comments

Ah ok. This seems to work. Does this have any pros/cons over using "del", for example: del session['foo']
Use pop when you need to know the value of deleted key.Use del otherwise.
Good to know. Thanks so much.
pop is my way of doing it. avoid del
Yes, and it depends upon your knowledge over the application. if you're sure about the session keys and values need not to check but we shouldn't trust the client always better to check if key existed or not then raise Exception.
5

I remember writing app that was poping elements very fast and it behaves weird (dont remember right now this specific case) but I used to use from then del everywhere i could.

If you want to remove key from session if it exist or not you can use pop:

flask.session.pop('key_name', None) 

with del it would be:

try: del flask.session['key_name'] except KeyError: pass 

I wrote this answer because of CSMaveric comments, about avoiding del.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.