15. Session in Flask

In Flask, "Session" refers to a way to persist data across requests. It allows Flask applications to remember information from one request to another, which is essential for maintaining user state, such as login sessions or storing user preferences.

How Sessions Work in Flask:

  1. Setting Up Sessions: To use sessions in Flask, you need to set a secret key. This key is used to cryptographically sign the session cookie, ensuring that the data stored in the session cannot be tampered with by the client.

    from flask import Flask, session
    
    app = Flask(__name__)
    app.secret_key = 'your_secret_key'
  2. Storing Data in Sessions: You can store data in the session object, which behaves like a dictionary:

    @app.route('/login', methods=['POST'])
    def login():
        username = request.form['username']
        # Check username and password
        if username == 'admin':
            session['logged_in'] = True
            return 'Logged in successfully!'
        else:
            return 'Login failed!'

    In this example, session['logged_in'] = True stores the fact that the user is logged in.

  3. Accessing Session Data: You can access session data similarly to accessing dictionary items:

    @app.route('/dashboard')
    def dashboard():
        if session.get('logged_in'):
            return 'Welcome to the dashboard!'
        else:
            return 'Access denied!'

    Here, session.get('logged_in') checks if the user is logged in.

  4. Removing Session Data: To remove data from the session, you can use the pop method:

    @app.route('/logout')
    def logout():
        session.pop('logged_in', None)
        return 'Logged out successfully!'

    This removes the 'logged_in' key from the session, effectively logging the user out.

Example Usage:

Here’s a simple example integrating sessions into a Flask application:

Explanation:

  • Setting Up: The secret_key is crucial for session security. It should be kept secret and not exposed in your code.

  • Storing Data: session['logged_in'] = True sets a session variable indicating the user is logged in.

  • Accessing Data: session.get('logged_in') checks if the user is logged in.

  • Removing Data: session.pop('logged_in') logs the user out by removing the 'logged_in' key from the session.

Sessions in Flask are versatile and essential for handling user authentication, maintaining user-specific data, and managing user interactions across multiple requests.

Last updated