Python Flask Login and Logout Example

Last Updated on May 11th, 2021 at 04:01 pm


The tutorial, Python login and logout example will show you how to login and logout a user using session in Python 3. You may need users to authenticate/authorize using credentials when there are protected areas in web application. For example, you need to authenticate when you are accessing your savings account details using netbanking.


Python 3.6.6 – 3.9.5, MySQL Database 5.6 – 8.0.22, Flask 1.1.1- 1.1.2


Please go through the following steps in order to implement Python login and logout example using Flask MySQL:

Step 1. Create the below script (py is the extension to indicate Python script) where I import the flask module. Notice how I create flask instance. Here you need to assign secret key otherwise session will not work in Python.

from flask import Flask

app = Flask(__name__)
app.secret_key = "secret key"

Step 2. I create the below Python script to setup the MySQL database configurations for connecting to database. I need to configure database connection with flask module and that’s why I have imported app module and setup the MySQL configuration with flask module.

from app import app
from flaskext.mysql import MySQL

mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'roytuts'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

Step 3. Next I need script. This script is the perfect instance of Python login and logout example using Flask and MySQL. It defines all required URIs for performing login and logout operations. It will also connect to MySQL database server and query the database to read.

Related Posts:

I have used login.html page for log in to the system but for home or index page I have only displaying html text instead of using template page. If you want you can use html template page for home or index page also.

import pymysql
from app import app
from db_config import mysql
from flask import flash, session, render_template, request, redirect
from werkzeug import generate_password_hash, check_password_hash

def index():
	if 'email' in session:
		username = session['email']
		return 'Logged in as ' + username + '<br>' + "<b><a href = '/logout'>click here to logout</a></b>"
	return "You are not logged in <br><a href = '/login'></b>" + "click here to login</b></a>"
def login():
	return render_template('login.html')

@app.route('/submit', methods=['POST'])
def login_submit():
	_email = request.form['inputEmail']
	_password = request.form['inputPassword']
	# validate the received values
	if _email and _password and request.method == 'POST':
		#check user exists			
		conn = mysql.connect()
		cursor = conn.cursor()
		sql = "SELECT * FROM tbl_user WHERE user_email=%s"
		sql_where = (_email,)
		cursor.execute(sql, sql_where)
		row = cursor.fetchone()
		if row:
			if check_password_hash(row[3], _password):
				session['email'] = row[1]
				return redirect('/')
				flash('Invalid password!')
				return redirect('/login')
			flash('Invalid email/password!')
			return redirect('/login')
def logout():
	session.pop('email', None)
	return redirect('/')

if __name__ == "__main__":

Step 4. Below is the login html page. In this page I display any error or success message which are stored in flash or session scope.

<doctype html>
<title>User Login - Python Flask</title>
	{% with messages = get_flashed_messages() %}
	  {% if messages %}
		<ul class=flashes>
		{% for message in messages %}
		  <li>{{ message }}</li>
		{% endfor %}
	  {% endif %}
	{% endwith %}
<form method="post" action="/submit">
			<input name="inputEmail" value="" type="text" placeholder="Email" required>
			<input name="inputPassword" value="" type="password" placeholder="Password" autocomplete="off" required>
		<input type="submit" value="Submit">

MySQL Table

For MySQL 5.6 version you can use the following structure:


CREATE TABLE `tbl_user` (
  `user_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `user_email` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `user_password` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`user_id`)

/*Data for the table `tbl_user` */

insert  into `tbl_user`(`user_id`,`user_name`,`user_email`,`user_password`) values 
(2,'Soumitra Roy','','pbkdf2:sha256:50000$g1GQ8Qen$7413b42b320fc47813b3188b52e08a6681be1c83d4eeec15ee6ca4b9fe8347ef');

For MySQL version 8.0.22 you can use the following sructure:

CREATE TABLE `tbl_user` (
  `user_id` bigint COLLATE utf8mb4_unicode_ci NOT NULL AUTO_INCREMENT,
  `user_name` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_email` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `user_password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`user_id`)

insert  into `tbl_user`(`user_id`,`user_name`,`user_email`,`user_password`) values 
(2,'Soumitra Roy','','pbkdf2:sha256:50000$g1GQ8Qen$7413b42b320fc47813b3188b52e08a6681be1c83d4eeec15ee6ca4b9fe8347ef');

Enough coding… let’s move on to testing…

Testing the Application

Now navigate to the project directory and execute the command python or, your server will start on default port 5000. If you want to change the port then you can change the line to, where 5001 is the new port.

Error on invalid email and password

python login and logout example

Error on invalid password

python login and logout example

Success on valid email and password(pwd)

python login and logout example

That’s all. Hope you got idea on Python login and logout Example using Flask and MySQL.

Source Code


4 Replies to “Python Flask Login and Logout Example”

  1. im getting error in saying that——
    ModuleNotFoundError: No module named ‘flaskext’
    please help me im stuck here….
    advance thank you

Leave a Reply

Your email address will not be published. Required fields are marked *