How to Create a Logout Button in Flask Python After a User is Logged In?

Estimated read time 3 min read

In Flask, you can create a logout button that logs a user out of your web application after they have logged in by using sessions.

Here’s an example of how to create a logout button in Flask:

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

app = Flask(__name__)
app.secret_key = 'mysecretkey'

# Login route
@app.route('/login')
def login():
    session['logged_in'] = True
    return redirect(url_for('home'))

# Logout route
@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    return redirect(url_for('home'))

# Home route
@app.route('/')
def home():
    if 'logged_in' in session:
        return render_template('home.html')
    else:
        return redirect(url_for('login'))

In this example, we define three routes: a login route, a logout route, and a home route. The login route sets a session variable called logged_in to True, which indicates that the user is logged in. The logout route removes the logged_in session variable using the pop() method, which logs the user out. The home route checks if the logged_in session variable is set, and renders the home page template if the user is logged in, or redirects to the login page if the user is not logged in.

To create a logout button in your Flask application, you can add a link to your HTML templates that points to the logout route. Here’s an example of how to create a logout button in an HTML template:

{% if 'logged_in' in session %}
    <p>Welcome, {{ session.username }}!</p>
    <form action="{{ url_for('logout') }}" method="post">
        <button type="submit" class="btn btn-primary">Logout</button>
    </form>
{% endif %}

In this example, we use Jinja template syntax to check if the logged_in session variable is set. If the user is logged in, we display a welcome message that includes their username (assuming that the username variable is also set in the session). We then create a form that points to the logout route using the url_for() function, and includes a logout button that the user can click to log out.

When the user clicks the logout button, the form is submitted to the logout route, which removes the logged_in session variable and redirects the user to the home page (or the login page, depending on your application logic).

Note that this is just an example of how to create a logout button in Flask. The exact implementation will depend on your specific application logic and requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply