Flask session redirects to login page
12:42 01 Feb 2022

I am currently in the process of building a flask based LAN chatting app (using sqlite3 to store usernames and socketio for messaging) and am having trouble implementing sessions correctly.

I have followed both this guide: https://www.techwithtim.net/tutorials/flask/sessions/ and read the documentation here https://flask-session.readthedocs.io/en/latest/ but am somehow still not getting my code to work:

In the login page, when the username is posted, I want users to be redirected to the chat-page.html, but this does not occur. Instead they are redirected to the login page, and I cannot figure out why:


from flask import Flask, render_template, request, flash, session, redirect, url_for


#creating the routes
@app.route('/login', methods=["POST", "GET"])
def login_form():

   if request.method == "POST":
       username = request.form.get("user_name")
       session["user"] = username
       return redirect(url_for('chat_page'))
   else:
       if "user" in session:
           return redirect(url_for('chat_page'))

       return render_template('login.html')


@app.route('/chat-page')
def chat_page():
   if "user" in session:
       username = session["user"]
       return render_template('chat-page.html', Uname=username)
   return redirect(url_for('login_form'))


@app.route("/logout")
def logout():
   session.pop("user", None)
   flash("You have been logged out!")
   return redirect(url_for('login_form'))


from flask_session import Session
app = Flask(__name__)
Session(app)
python flask session httprequest