Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you "clear" only specific Flask session variables?

Tags:

python

flask

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.

like image 667
Source Matters Avatar asked Sep 23 '18 06:09

Source Matters


2 Answers

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

# remove the keyname from the session if it is there
session.pop('key_name')
like image 58
Chandu codes Avatar answered Nov 08 '22 06:11

Chandu codes


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.

like image 5
Abc Xyz Avatar answered Nov 08 '22 05:11

Abc Xyz