I've been using session variables with flask for some pretty simple things but I'm getting behavior I don't quite understand. I have a logout button that links to the logout function, where I want to remove the username from the session if there currently is one. This ends up having no effect however, and I've had a lot of trouble finding out how to fix this problem
Here are the the import/setup statements that should be related, this portion is copied from a lessons starter code
from flask_session import Session
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
In the index function, I check if the username is set and pass it into the template
@app.route("/")
def index():
logged_in = False
username = None
if session.get('username') is not None:
username = session['username']
logged_in = True
return render_template("index.html", logged_in=logged_in, username=username)
The logout should just remove the username from the session if there is one and then redirect to the index
@app.route("/logout")
def logout():
if session.get('username') is not None:
session.pop('username', None)
return redirect(url_for('index'))
Through trying to fix this problem, I've noticed that the logout function works how I want it to when called, affecting the session, but after the redirect the changes seem to be reverted/ignored. From this I assume it's something I'm not understanding about the redirect function but I really have no idea.
Here's the login function where the username is set if that helps, thanks.
@app.route("/login", methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return redirect(url_for('index'))
else:
username = request.form.get("username")
password = request.form.get("password")
result = (db.execute('SELECT username FROM users where username = :username AND password = :password',
{"username": username, "password": password}).fetchone())
if result is not None:
session['username'] = username
return redirect(url_for('library'))
else:
return redirect(url_for('index'))