Login Page Using Flask And Mysql

I can recall the initial instance when I constructed a Flask and MySQL-based login page. It was an exhilarating moment witnessing individuals safely logging into their customized accounts on my webpage. In this article, I will lead you through the steps of developing a login page using Flask and MySQL, while also sharing some of my own insights and thoughts along the journey.

Getting Started with Flask

If you’re new to Flask, it’s a lightweight web framework that allows you to build web applications with ease. To begin, make sure you have Flask installed. If not, you can install it by running the following command in your terminal:

pip install flask

Once Flask is installed, create a new directory for your project and navigate to it in your terminal. Then, create a new Python file, let’s call it app.py, and open it in your favorite text editor.

Setting up the Flask App

Now that we have our project structure ready, let’s import the necessary modules and set up our Flask app. In your app.py file, add the following code:


from flask import Flask, render_template, request, redirect, url_for
import mysql.connector

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'

# Your code here...

Here, we import the necessary modules: Flask for creating the web application, render_template for rendering the HTML templates, request for handling HTTP requests, redirect for redirecting to different routes, url_for for generating URLs, and mysql.connector for connecting to MySQL database.

Connecting to the MySQL Database

Before we can create our login page, we need to establish a connection to the MySQL database. Assuming you have MySQL already installed, add the following code below the previous section:


mydb = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)

Make sure to replace your_username, your_password, and your_database with your actual MySQL credentials. This code connects our Flask app to the MySQL database, allowing us to interact with data stored in the database.

Creating the Login Page

Now comes the exciting part: creating the login page itself. In Flask, we use HTML templates to define the structure and layout of our web pages. Create a new directory called templates in your project directory, and inside it, create a new file called login.html.

In login.html, add the following code:





Login Page

Welcome to the Login Page



This code defines a basic HTML structure with the title “Login Page” and a heading “Welcome to the Login Page”. We’ll add the login form in the next section.

Adding the Login Form

To create the login form, add the following code inside the <!-- Your login form here... --> section in login.html:




This code creates a basic login form with two input fields, one for the username and another for the password, and a submit button. The form’s POST method specifies that the data should be sent securely. The action attribute defines the route where the form data will be submitted for authentication.

Handling the Login Request

Now let’s handle the login request in our Flask app. In app.py, add the following code below the previous sections:


@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']

# Your authentication code here...

This code defines a new route /login that only accepts POST requests. Inside the login function, we retrieve the username and password entered by the user from the form data.

Performing Authentication

Now that we have the user’s credentials, we can perform the authentication. Assuming you have a users table in your MySQL database with columns username and password, add the following code below the previous section:


cursor = mydb.cursor()
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
user = cursor.fetchone()

if user is None:
return 'Invalid username or password'
else:
return 'Login successful!'

This code uses the execute method to execute a SQL query that selects the user from the database based on the provided username and password. If the user is found, we return the message ‘Login successful!’. Otherwise, we return ‘Invalid username or password’.

Conclusion

Building a login page using Flask and MySQL can be a challenging yet rewarding experience. We have covered the initial setup, connecting to the MySQL database, creating the login page, handling the login request, and performing authentication. With this knowledge, you can now expand your application by adding additional features such as user registration, password recovery, and more. Good luck and happy coding!