In this article, I will walk you through the steps of building a login page in Python that connects to a database. As a developer, I have encountered the need for user authentication in several of my projects. After completing this tutorial, you will have a strong grasp on how to create a secure login page in Python utilizing a database.
Setting up the Database
The first step is to set up a database to store the user credentials. For this tutorial, I will be using MySQL as the database. Make sure you have MySQL installed on your system and create a new database. You can use the following command to do so:
CREATE DATABASE mydatabase;
Next, we need to create a table to store the user information. The table should have columns for the username and password. Use the following command to create the table:
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255), password VARCHAR(255));
Creating the Login Page
Now that we have our database set up, we can start creating our login page. The login page will consist of an HTML form with fields for the username and password. We will use Flask, a web framework for Python, to handle the form submission and authentication process.
Start by creating a new directory for your project and navigate to it in your terminal. Then, create a new Python file called app.py
and open it in your preferred text editor.
In the app.py
file, import Flask and create a new instance of the Flask class:
from flask import Flask
app = Flask(__name__)
Next, define a route for the login page. This route will handle the GET and POST requests for the login page. In the GET request, we will render the login form, and in the POST request, we will handle the form submission and authentication.
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# Perform authentication logic here
return render_template('login.html')
Inside the POST request, we retrieve the username and password from the form using the request.form
object. We will perform the authentication logic later in the code.
Now, let’s create the HTML template for the login page. Create a new directory called templates
inside your project directory and create a new file called login.html
inside the templates
directory. Add the following code to the login.html
file:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="/login" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
This HTML code creates a simple login form with fields for the username and password. The form submits a POST request to the /login
route.
Performing Authentication
Now that we have the login page set up, we need to add the authentication logic. In the app.py
file, add the following code inside the POST request of the /login
route:
if username and password:
# Connect to the database
db = MySQLdb.connect(host="localhost", user="yourusername", password="yourpassword", database="mydatabase")
cursor = db.cursor()
# Execute the query to check if the user exists
query = "SELECT * FROM users WHERE username = %s AND password = %s"
cursor.execute(query, (username, password))
result = cursor.fetchone()
if result:
return "Login successful"
else:
return "Invalid username or password"
In the code above, we first connect to the database using the credentials you provided. Then, we execute a query to check if the user with the given username and password exists in the database. If the query returns a result, we return the message “Login successful”. Otherwise, we return the message “Invalid username or password”.
Conclusion
Congratulations! You have successfully created a login page in Python with a database. In this tutorial, we covered the basics of setting up a database, creating the login page using Flask, and performing authentication.
Remember, user authentication is a critical aspect of any application that deals with sensitive information. Make sure to follow best practices for securing user credentials, such as hashing and salting passwords.
If you want to learn more about Flask, databases, or web development in Python, check out the following resources:
Happy coding!