Flask MySql Login and Registration With Session


In this tutorial we will create a simple Login system using the Python Flask and MySQL.

Flask MySql Login and Registration With Session

First, we have to install Flask package

pip install flask

install Flask-MySQLdb

pip install flask-mysqldb

Creating Database :

CREATE DATABASE `db_sample`;

CREATE TABLE  `db_sample`.`users` (
  `UID` int(11) NOT NULL AUTO_INCREMENT,
  `UNAME` varchar(50) NOT NULL,
  `EMAIL` varchar(50) NOT NULL,
  `UPASS` varchar(50) NOT NULL,
  PRIMARY KEY (`UID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

File Structure:

Flask MySql Login and Registration With Session

Creating Project :

  1. Create a folder 'loginapp'.
  2. Create 'app.py' file inside of 'loginapp' folder.

app.py

Write the following code in 'app.py' file


from flask import Flask,render_template,request,redirect,session,flash,url_for
from functools import wraps
from flask_mysqldb import MySQL

app=Flask(__name__)
app.config['MYSQL_HOST']='localhost'
app.config['MYSQL_USER']='root'
app.config['MYSQL_PASSWORD']=''
app.config['MYSQL_DB']='db_sample'
app.config['MYSQL_CURSORCLASS']='DictCursor'
mysql=MySQL(app)
 
#Login
@app.route('/') 
@app.route('/login',methods=['POST','GET'])
def login():
    status=True
    if request.method=='POST':
        email=request.form["email"]
        pwd=request.form["upass"]
        cur=mysql.connection.cursor()
        cur.execute("select * from users where EMAIL=%s and UPASS=%s",(email,pwd))
        data=cur.fetchone()
        if data:
            session['logged_in']=True
            session['username']=data["UNAME"]
            flash('Login Successfully','success')
            return redirect('home')
        else:
            flash('Invalid Login. Try Again','danger')
    return render_template("login.html")
  
#check if user logged in
def is_logged_in(f):
	@wraps(f)
	def wrap(*args,**kwargs):
		if 'logged_in' in session:
			return f(*args,**kwargs)
		else:
			flash('Unauthorized, Please Login','danger')
			return redirect(url_for('login'))
	return wrap
  
#Registration  
@app.route('/reg',methods=['POST','GET'])
def reg():
    status=False
    if request.method=='POST':
        name=request.form["uname"]
        email=request.form["email"]
        pwd=request.form["upass"]
        cur=mysql.connection.cursor()
        cur.execute("insert into users(UNAME,UPASS,EMAIL) values(%s,%s,%s)",(name,pwd,email))
        mysql.connection.commit()
        cur.close()
        flash('Registration Successfully. Login Here...','success')
        return redirect('login')
    return render_template("reg.html",status=status)

#Home page
@app.route("/home")
@is_logged_in
def home():
	return render_template('home.html')
    
#logout
@app.route("/logout")
def logout():
	session.clear()
	flash('You are now logged out','success')
	return redirect(url_for('login'))
    
if __name__=='__main__':
    app.secret_key='secret123'
    app.run(debug=True)

Creating HTML Page :

  1. Create the 'templates' folder inside of 'webapp' folder for creating HTML page.
  2. Create layout.html, login.html, reg.html and home.html files inside of 'templates' folder.

layout.html

Write the following html code in 'layout.html' file

<!DOCTYPE html>
<html>
  <head>
    <title>Pyton Flask-MySql Registraion, Login With Session</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md bg-light navbar-light">
      <div class='container'>
        <!-- Brand -->
        <a class="navbar-brand" href="/">Flask-MySql Registraion, Login</a>

        <!-- Toggler/collapsibe Button -->
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
          <span class="navbar-toggler-icon"></span>
        </button>

        <!-- Navbar links -->
        <div class="collapse navbar-collapse" id="collapsibleNavbar">
          <ul class="navbar-nav ml-auto">
            {% if session.username %}
              <li class="nav-item">
                <a class="nav-link" href="/home">Welcome : {{session.username}}</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="/logout">Logout</a>
              </li>
            {% else %}
              <li class="nav-item">
                <a class="nav-link" href="/login">Login</a>
              </li>
                <li class="nav-item">
              <a class="nav-link" href="/reg">Registration</a>
              </li>
            {% endif %}
          </ul>
        </div>
      </div>
    </nav>
    <div class='container mt-4'>
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% if messages %}
        {% for category, message in messages %}
          <div class="alert alert-{{ category }}">{{ message }}</div>
        {% endfor %}
      {% endif %}
    {% endwith %}
    
    {% block body %}

    {% endblock %}
    </div>
  </body>
</html>

login.html

Write the following html code in 'login.html' file


{% extends 'layout.html' %}
{% block body %}
  <div class='row mt-5'>
    <div class='col-4 mx-auto'>
      <h4 class='text-center'>User Login</h4><hr>
      <form action="{{url_for('login')}}" method='post'>
        <div class='form-group'>
          <label>Email</label>
          <input type='email' name='email' required class='form-control'>  
        </div>
        <div class='form-group'>
          <label>Password</label>
          <input type='password' name='upass' required class='form-control'>  
        </div>
        <input type='submit' name='submit' value='Submit' class='btn btn-success'>
      </form>
    </div>
  </div>
{% endblock %}

reg.html

Write the following code in 'reg.html' file


{% extends 'layout.html' %}
{% block body %}
  <div class='row mt-5'>
    <div class='col-4 mx-auto'>
      <h4 class='text-center'>User Registration</h4><hr>
      <form action="{{url_for('reg')}}" method='post'>
        <div class='form-group'>
          <label>User Name</label>
          <input type='text' name='uname' required class='form-control'>  
        </div>
        <div class='form-group'>
          <label>Email</label>
          <input type='email' name='email' required class='form-control'>  
        </div>
        <div class='form-group'>
          <label>Password</label>
          <input type='password' name='upass' required class='form-control'>  
        </div>
        <input type='submit' name='submit' value='Submit' class='btn btn-success'>
      </form>
    </div>
  </div>
{% endblock %}

home.html

Write the following code in 'home.html' file


{% extends 'layout.html' %}
{% block body %}
  <h3 class='jumbotron'>Welcome : {{session.username}}</h3>
{% endblock %}

Run the Project:

  1. Run 'app.py' file.
  2. Browse the URL 'localhost:5000'.

Output:

Flask MySql Login and Registration With Session Flask MySql Login and Registration With Session Flask MySql Login and Registration With Session