How to clear a flask session?

When importing a jar, we import modules such as session , etc.

SecureCookieSession is a kind of dictionary that can be accessed through a session.

Now I'm trying to clear all the unnecessary variables that I used when creating the site.

One answer to stackoverflow used a command like session.clear() to clear the contents of a session. But such a command gives an error that such a command does not exist.

Can someone tell me how to clear the SecureCookieSession and how to clear the session every time I turn off the server or close the website?

+18
source share
4 answers

There is no clear session or nothing.

You just need to change app.config["SECRET_KEY"] , and the contents in the session dictionary will be erased.

-17
source
 from flask import session session.clear() 

I use such a jar session, it works. I do not use SecureCookieSession , although perhaps this may help.

+52
source

You can also iterate over the session and call session.pop() for each key in the session. Pop will remove the variable from the session and you won’t have to update the secret key.

 for key in session.keys(): session.pop(key) 
+18
source

As stated in Jerry Unhaptai's answer , as well as in the relevant section of the Flask documentation , you can simply do:

 from flask import session session.clear() 

Although, as Alejandro rightly pointed out in a comment:

If you also use reprogrammed messages in your application, you should be aware that reprogrammed messages are stored in session and therefore can be deleted before they flash if you clear session .

My suggestion is to take advantage of list comprehension:

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

in fact, this is the same for loop as in TheF1rstPancake's answer , albeit with a single line . We can delete everything except flashed messages from session (or add add any other conditions, for that matter) quite easily, for example, like this:

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

Source: https://habr.com/ru/post/980438/


All Articles