Open In App

Login and Registration Project Using Flask and MySQL

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Project Title: Login and registration Project using Flask framework and MySQL Workbench. Type of Application (Category): Web application. Introduction: A framework is a code library that makes a developer’s life easier when building web applications by providing reusable code for common operations. There are a number of frameworks for Python, including Flask, Tornado, Pyramid, and Django. Flask is a lightweight web application framework. It is classified as a micro-framework because it does not require particular tools or libraries. Pre-requisite: Knowledge of Python, MySQL Workbench and basics of Flask Framework. Python and MySQL Workbench should be installed in the system. Visual studio code or Spyder or any code editor to work on the application. Technologies used in the project: Flask framework, MySQL Workbench. Implementation of the Project: (1) Creating Environment Step-1: Create an environment. Create a project folder and a venv folder within.

py -3 -m venv venv

Step-2: Activate the environment.

venv\Scripts\activate

Step-3: Install Flask.

pip install Flask

(2) MySQL Workbench Step-1: Install MySQL workbench. Link to install : https://dev.mysql.com/downloads/workbench/ Know more about it : https://www.mysql.com/products/workbench/ Step-2: Install ‘mysqlbd’ module in your venv.

pip install flask-mysqldb

Step-3: Open MySQL workbench. Step-4: Write the following code. The above SQL statement will create our database geeklogin with the table accounts. Step-5: Execute the query. (3) Creating Project Step-1: Create an empty folder ‘login’. Step-2: Now open your code editor and open this ‘login’ folder. Step-3: Create ‘app.py’ folder and write the code given below. 

Python3




# Store this code in 'app.py' file
 
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
 
 
app = Flask(__name__)
 
 
app.secret_key = 'your secret key'
 
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'your password'
app.config['MYSQL_DB'] = 'geeklogin'
 
mysql = MySQL(app)
 
@app.route('/')
@app.route('/login', methods =['GET', 'POST'])
def login():
    msg = ''
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        username = request.form['username']
        password = request.form['password']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM accounts WHERE username = % s AND password = % s', (username, password, ))
        account = cursor.fetchone()
        if account:
            session['loggedin'] = True
            session['id'] = account['id']
            session['username'] = account['username']
            msg = 'Logged in successfully !'
            return render_template('index.html', msg = msg)
        else:
            msg = 'Incorrect username / password !'
    return render_template('login.html', msg = msg)
 
@app.route('/logout')
def logout():
    session.pop('loggedin', None)
    session.pop('id', None)
    session.pop('username', None)
    return redirect(url_for('login'))
 
@app.route('/register', methods =['GET', 'POST'])
def register():
    msg = ''
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form :
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM accounts WHERE username = % s', (username, ))
        account = cursor.fetchone()
        if account:
            msg = 'Account already exists !'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            msg = 'Invalid email address !'
        elif not re.match(r'[A-Za-z0-9]+', username):
            msg = 'Username must contain only characters and numbers !'
        elif not username or not password or not email:
            msg = 'Please fill out the form !'
        else:
            cursor.execute('INSERT INTO accounts VALUES (NULL, % s, % s, % s)', (username, password, email, ))
            mysql.connection.commit()
            msg = 'You have successfully registered !'
    elif request.method == 'POST':
        msg = 'Please fill out the form !'
    return render_template('register.html', msg = msg)


Step-4: Create the folder ‘templates’. create the file ‘login.html’, ‘register.html’, ‘index.html’ inside the ‘templates’ folder. Step-5: Open ‘login.html’ file and write the code given below. In ‘login.html’, we have two fields i.e. username and password. When user enters correct username and password, it will route you to index page otherwise ‘Incorrect username/password’ is displayed. 

html




<!-- Store this code in 'login.html' file inside the 'templates' folder -->
 
<html>
    <head>
        <meta charset="UTF-8">
        <title> Login </title>
        <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">          
    </head>
    <body></br></br></br></br></br>
        <div align="center">
          <div align="center" class="border">
             <div class="header">
                <h1 class="word">Login</h1>
             </div></br></br></br>
            <h2 class="word">
                <form action="{{ url_for('login') }}" method="post">
                  <div class="msg">{{ msg }}</div>
                    <input id="username" name="username" type="text" placeholder="Enter Your Username" class="textbox"/></br></br>
                    <input id="password" name="password" type="password" placeholder="Enter Your Password" class="textbox"/></br></br></br>
                    <input type="submit" class="btn" value="Sign In"></br></br>
                </form>
            </h2>
            <p class="bottom">Don't have an account?  <a class="bottom" href="{{url_for('register')}}"> Sign Up here</a></p>
          </div>
        </div>
    </body>
</html>


Step-6: Open ‘register.html’ file and write the code given below. In ‘register.html’, we have three fields i.e. username, password and email. When user enters all the information, it stored the data in the database and ‘Registration successful’ is displayed. 

html




<!-- Store this code in 'register.html' file inside the 'templates' folder -->
 
<html>
    <head>
        <meta charset="UTF-8">
        <title> Register </title>
        <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">             
    </head>
    <body></br></br></br></br></br>
        <div align="center">
          <div align="center" class="border">
             <div class="header">
                <h1 class="word">Register</h1>
             </div></br></br></br>
            <h2 class="word">
                <form action="{{ url_for('register') }}" method="post">
                  <div class="msg">{{ msg }}</div>
                    <input id="username" name="username" type="text" placeholder="Enter Your Username" class="textbox"/></br></br>
                    <input id="password" name="password" type="password" placeholder="Enter Your Password" class="textbox"/></br></br>
                    <input id="email" name="email" type="text" placeholder="Enter Your Email ID" class="textbox"/></br></br>
                    <input type="submit" class="btn" value="Sign Up"></br>
                </form>
            </h2>
            <p class="bottom">Already have an account?  <a class="bottom" href="{{url_for('login')}}"> Sign In here</a></p>
          </div>
        </div>
    </body>
</html>


Step-7: Open ‘index.html’ file and write the code given below. This page is displayed when login is successful and username is also displayed. The logout functionality is also included in this page. When user logs out, it moves to fresh login page again. 

html




<!-- Store this code in 'index.html' file inside the 'templates' folder-->
 
<html>
    <head>
        <meta charset="UTF-8">
        <title> Index </title>
        <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">                    
    </head>
    <body></br></br></br></br></br>
        <div align="center">
          <div align="center" class="border">
             <div class="header">
                <h1 class="word">Index</h1>
             </div></br></br></br>
                <h1 class="bottom">
                     Hi {{session.username}}!!</br></br> Welcome to the index page...                
                </h1></br></br></br>
                <a href="{{ url_for('logout') }}" class="btn">Logout</a>
          </div>
        </div>
    </body>
</html>


Step-8: Create the folder ‘static’. create the file ‘style.css’ inside the ‘static’ folder and paste the given CSS code. 

css




/* Store this code in 'style.css' file inside the 'static' folder*/
 
            .header{
                padding: 5px 120px;
                width: 150px;
                height: 70px;
                background-color: #236B8E;
            }
         
            .border{
                padding: 80px 50px;
                width: 400px;
                height: 450px;
                border: 1px solid #236B8E;
                border-radius: 0px;
                background-color: #9AC0CD;
            }
 
            .btn {
                padding: 10px 40px;
                background-color: #236B8E;
                color: #FFFFFF;
                font-style: oblique;
                font-weight: bold;
                border-radius: 10px;
            }
 
            .textbox{
                padding: 10px 40px;
                background-color: #236B8E;
                text-color: #FFFFFF;
                border-radius: 10px;
            }
                 
            ::placeholder {
                color: #FFFFFF;
                opacity: 1;
                font-style: oblique;
                font-weight: bold;
            }
 
            .word{
                color: #FFFFFF;
                font-style: oblique;
                font-weight: bold;
            }
 
            .bottom{
                color: #236B8E;
                font-style: oblique;
                font-weight: bold;
            }


Step-9: The project structure will look like this. (4) Run the Project Step-1: Run the server. Step-2: Browse the URL ‘localhost:5000’. Step-3: The output web page will be displayed. (5) Testing of the Application Step-1: If you are new user, go to sign up page and fill the details. Step-2: After registration, go to login page. Enter your username and password and sign in. Step-3: If your login is successful, you will be moved to index page and your name will be displayed. Output: Login page: Registration page: If registration successful: Before registration, Database table: After registration, Database table: If login successful, Indexpage is displayed: If Login fails:



Last Updated : 09 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads