Login Page in Flask Using Sessions
#app.py from flask import Flask, request, session, redirect, url_for, render_template, g import os app = Flask(__name__) app.secret_key = os.urandom(24) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': session.pop('user', None) if request.form['password'] == 'password': session['user'] = request.form['username'] return redirect(url_for('protected')) return render_template('index.html') @app.route('/protected') def protected(): if g.user: return render_template('protected.html') return redirect(url_for('index')) @app.before_request def before_request(): g.user = None if 'user' in session: g.user = session['user'] @app.route('/getsession') def getsession(): if 'user' in session: return session['user'] return 'Not logged in!' @app.route('/dropsession') def dropsession(): session.pop('user', None) return 'Dropped!' if __name__ == '__main__': app.run(debug=True)
//index.html <html> <head> <title>Login Page</title> </head> <body> <h1>Login Page in Flask Using Sessions</h1> <h1>Please login</h1> <form method="POST"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit"> </form> </body> </html>
//protected.html <html> <head> <title>Protected Page</title> </head> <body> <h1>Welcome to the protected page!</h1> </body> </html>