Login and Registration Project in Flask using MySQL
0 1108
Introduction
Creating a secure and functional login and registration system is an essential part of most web applications. In this blog, we'll build a simple Login and Registration Project in Flask using MySQL. This project includes user sign-up, login, session handling, and database connectivity — all vital components of any authentication system.
Prerequisites
To follow along, make sure you have the following installed:
- Python 3.x
- Flask
- MySQL Server
- MySQL Connector for Python
Step 1: Setting Up the Flask Project Structure
Start by creating a new directory for your project. Inside it, create the following files:
app.py– main application filetemplates/– folder containing HTML templates
Step 2: Install Required Packages
pip install flask
pip install mysql-connector-python
Step 3: Create the MySQL Database
Open your MySQL client and run the following commands to create a database and users table:
CREATE DATABASE flask_auth;
USE flask_auth;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL
);
Step 4: Building the Flask App
from flask import Flask, render_template, request, redirect, session
import mysql.connector
import hashlib
app = Flask(__name__)
app.secret_key = 'your_secret_key'
conn = mysql.connector.connect(
host='localhost',
user='root',
password='your_password',
database='flask_auth'
)
cursor = conn.cursor()
@app.route('/')
def home():
return render_template('login.html')
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = hashlib.sha256(request.form['password'].encode()).hexdigest()
cursor.execute('SELECT * FROM users WHERE username=%s AND password=%s', (username, password))
user = cursor.fetchone()
if user:
session['username'] = username
return redirect('/dashboard')
else:
return 'Invalid credentials'
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
password = hashlib.sha256(request.form['password'].encode()).hexdigest()
cursor.execute('INSERT INTO users (username, email, password) VALUES (%s, %s, %s)',
(username, email, password))
conn.commit()
return redirect('/')
return render_template('register.html')
@app.route('/dashboard')
def dashboard():
if 'username' in session:
return f'Welcome, {session["username"]}!'
return redirect('/')
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
Step 5: Create HTML Templates
login.html
<form method="POST" action="/login">
<input type="text" name="username" placeholder="Username" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<button type="submit">Login</button>
<p>Don't have an account? <a href="/register">Register here</a></p>
</form>
register.html
<form method="POST" action="/register">
<input type="text" name="username" placeholder="Username" required><br>
<input type="email" name="email" placeholder="Email" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<button type="submit">Register</button>
</form>
Conclusion
You've now created a complete login and registration system in Flask using MySQL as the backend database. This project can serve as a strong foundation for more advanced applications involving role-based access, password hashing libraries like bcrypt, and user verification via email or tokens.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments