flask
  1. flask-session

Session - Web Templating in Flask

Syntax

from flask import Flask, session, redirect, url_for

app = Flask(__name__)
app.secret_key = "your_secret_key"

@app.route('/login')
def login():
    session['username'] = 'user_name'
    return redirect(url_for('home'))
  
@app.route('/home')
def home():
    if 'username' in session:
        return f"Welcome {session['username']}!"
    else:
        return redirect(url_for('login'))

if __name__ == '__main__':
    app.run(debug=True)

Example

from flask import Flask, session, redirect, url_for

app = Flask(__name__)
app.secret_key = "my_secret_key"

@app.route('/')
def index():
    if 'username' in session:
        username = session['username']
        return f"Hello, {username}!<br><a href ='/logout'>Logout</a>"
        
    return "You are not logged in!<br><a href = '/login'>Login</a>"

@app.route('/login', methods = ['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if username == 'admin' and password == 'admin':
            session['username'] = username
            return redirect(url_for('index'))

    return '''
        <form method = "post">
            <p><input type = text       name = username></p>
            <p><input type = password   name = password></p>
            <p><input type = submit     value = "Login"></p>
        </form>
    '''

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('index'))

if __name__ == "__main__":
    app.run(debug=True)

Output

Explanation

Sessions in Flask are used to store user data on the server side. Flask facilitates the creation and management of sessions through its inbuilt module.

In the above example, we first import the necessary modules like Flask, session, and redirect to use their functions and methods.

A secret key is needed to create a session. The secret key is used to generate a unique session ID for each user, and it also encrypts the data stored in the session. Thus, it is necessary to secure this key.

In the /login route, we set the value of session['username'] to the name of the user who has logged in. In the /home route, we check if the username exists in the session. If it does, we display a personalized welcome message for the user.

If a user tries to access the /home route without logging in, he/she will be redirected to the /login route.

Use

Sessions in Flask can be used for:

  • User Authentication
  • Storing User Preferences and Settings
  • Form Data Persistence
  • Shopping Cart Items
  • Passive Login, etc.

Important Points

  • A secret key is needed to establish a session in Flask
  • Storing sensitive information in sessions like passwords is not recommended
  • Flask can handle sessions through the built-in session module.

Summary

In this tutorial, we covered the use of session in Flask. We covered the syntax, example, output, and explanation of using sessions in Flask. Sessions can be used for user authentication, form data persistence, and shopping cart items. Sessions should be used carefully and the secret key should be properly secured.

Published on: