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.
from session.keys()
have you tried popping out keys?
# remove the keyname from the session if it is there
session.pop('key_name')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With