Flask HTTP methods, handle GET & POST requests

Creating a simple login system in Flask involves handling HTTP POST requests to process login credentials and managing user sessions. Here's a step-by-step guide to building a basic login system.
 
 
 
Flask HTTP methods, handle GET & POST requests

 
 

Step 1: Set Up Flask


First, ensure Flask is installed:
 
 
 


pip install Flask

 

Read also: Flask Tutorial: Templates 

 

Step 2: Create the Flask Application


Create a file named `app.py` and add the following code:


 




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

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

# Dummy user data
users = {
    'admin': 'password123'
}

@app.route('/')
def home():
    if 'username' in session:
        return f'Logged in as {session["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 in users and users[username] == password:
            session['username'] = username
            flash('Login successful!')
            return redirect(url_for('home'))
        else:
            flash('Invalid credentials, please try again.')
    return render_template('login.html')

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

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



Step 3: Create the HTML Templates


Create a folder named `templates` in the same directory as `app.py`. Inside the `templates` folder, create a file named `login.html` with the following content:

 

 




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}
    <form action="/login" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required>
        <br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
        <br>
        <button type="submit">Login</button>
    </form>
</body>
</html>


Read also: Implementing Basic Add to cart functionality in python using Flask

 

Flask HTTP methods, handle GET & POST requests

 
Flask HTTP methods, handle GET & POST requests

 

Step 4: Explanation of the Code


1. Setting Up Flask: The `app` object is created and configured with a secret key to handle sessions securely.

2. Dummy User Data: A dictionary `users` is created to store usernames and passwords. In a real application, you would use a database.

3. Home Route: The home route (`/`) checks if the user is logged in by looking for the `username` in the session. If logged in, it displays a welcome message and a logout link. If not, it displays a login link.

4. Login Route: The login route (`/login`) handles both GET and POST requests. 
 
  •     GET Request: Renders the login form.
  •     POST Request: Processes the form data, checks the credentials, and sets the session. If the credentials are incorrect, it flashes an error message.

5. Logout Route: The logout route (`/logout`) removes the username from the session and redirects to the home page.

6. Flashing Messages: Flash messages are used to provide feedback to the user (e.g., login success or failure). These messages are displayed in the `login.html` template.
 

Step 5: Running the Application


Run your Flask application by executing the following command:
 
 


python app.py

or 

Just -> flask run

 
Flask HTTP methods, handle GET & POST requests

 
 
Navigate to `http://127.0.0.1:5000/` in your web browser. You will see the login link. Click on it, enter the credentials (`admin` / `password123`), and submit the form. If the credentials are correct, you will be logged in and redirected to the home page. You can then log out using the provided link.

This basic example demonstrates how to handle HTTP POST requests in Flask to create a simple login system. For a more secure and scalable application, consider integrating with a database and implementing proper password hashing and user authentication mechanisms.
Previous Post Next Post