user4413310
user4413310

Reputation: 471

How do I clear a flask session?

While importing flask, we import modules such as session etc.

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

Now, I try to clear all the junk variables that I used while trying to build a website.

One of the answers on stackoverflow used a command like session.clear() for clearing the contents of a session. But such a command gives an error that no such command exists.

Can anyone point out for me how to clear the SecureCookieSession and how to clear the session every time I shutdown the server or close the website?

Upvotes: 46

Views: 106361

Answers (7)

user8554766
user8554766

Reputation:

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

from flask import session

session.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 any other conditions, for that matter) quite easily, like so:

[session.pop(key) for key in list(session.keys()) if not key.startswith('_')]

Upvotes: 30

bauderr
bauderr

Reputation: 87

TO use session.clear() you first need to set up your session environment in /home/username/www/flask_app.py

It looks something like this below. Notice how I import Session with a capital Session

#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import annotations

from datetime import timedelta
from flask import Flask
from flask_session.__init__ import Session

app = Flask(__name__)
app.config['SERVER_NAME'] = "www.mslscript.com"
app.secret_key = 'adsfkljasdfjsd982134ifdh434df4890g'
app.config["SESSION_PERMANENT"] = True
app.config["SESSION_TYPE"] = "filesystem"
app.config['SESSION_FILE_THRESHOLD'] = 250   # 500 is default
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=10)
Session(app)

from website.views import views
from website.auth import auth

app.register_blueprint(views, url_prefix='/')
app.register_blueprint(auth, url_prefix='/')

website is a directory with the views.py and auth.py files which contain the line:

auth = Blueprint('auth', __name__, template_folder='templates', static_folder='static')

Which I assume you recognize as also having the line

@auth.route('/login.html', methods=['GET', 'POST'])

Inside this auth.py and views.py or __init__.py you can use the line from flask import session and therefore session.clear() and session['username'] = 'Ashburry' but session.pop(key, None) is the standard convention we have come to agree on; atleast only if you use flash(f"hello {session['username']}") or just flash()

I host my website on PythonAnywhere.com so it is easier for me to setup the server than having to use the app.run() command manually, with the setup included. If you are not using PythonAnywhere.com you cannot copy/paste this code you will have to take from it what you need and adapt it to your own app.run('127.0.0.1', 1234)

Upvotes: 0

TheF1rstPancake
TheF1rstPancake

Reputation: 2378

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)

Upvotes: 28

Prashant Shrivastava
Prashant Shrivastava

Reputation: 713

There is no way to clear session or anything.

One must simply change the app.config["SECRET_KEY"] and the contents in session dictionary will get erased.

Upvotes: -44

Carson
Carson

Reputation: 8098

If you want to pop and put it to g, you can try:

from flask import g, session

my_value_list = ('sys_info', 'msg')
[setattr(g, s_k, session.pop(s_k)) for s_k in my_value_list if s_k in session.keys()]

Upvotes: 0

bsplosion
bsplosion

Reputation: 2886

As an additional option, if you're using the flask_login package, all you have to do is call logout_user in the context of a request.

The logout_user function pops the session key as mentioned in other answers, while also cleaning up the remember cookie and forcing a reload of the user in the login_manager. It also sends a logged-out signal (if signal handling is important in your app).

from flask_login import logout_user
logout_user()

Upvotes: 0

Jerry Unkhaptay
Jerry Unkhaptay

Reputation: 1338

from flask import session

session.clear()

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

Upvotes: 122

Related Questions