Python Flask Login and Logout Example

Introduction

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.

Prerequisites

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

Login/Logout

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

Step 1. Create the below app.py 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 db_config.py 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'
mysql.init_app(app)

Step 3. Next I need main.py 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

@app.route('/')
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>"
	
@app.route('/login')
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]
				cursor.close() 
				conn.close()
				return redirect('/')
			else:
				flash('Invalid password!')
				return redirect('/login')
		else:
			flash('Invalid email/password!')
			return redirect('/login')
		
@app.route('/logout')
def logout():
	session.pop('email', None)
	return redirect('/')

if __name__ == "__main__":
    app.run()

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>
<h2>Login</h2>
<p>
	{% with messages = get_flashed_messages() %}
	  {% if messages %}
		<ul class=flashes>
		{% for message in messages %}
		  <li>{{ message }}</li>
		{% endfor %}
		</ul>
	  {% endif %}
	{% endwith %}
</p>
<form method="post" action="/submit">
    <dl>
		<p>
			<input name="inputEmail" value="" type="text" placeholder="Email" required>
		</p>
		<p>
			<input name="inputPassword" value="" type="password" placeholder="Password" autocomplete="off" required>
		</p>
    </dl>
    <p>
		<input type="submit" value="Submit">
	</p>
</form>

MySQL Table

For MySQL 5.6 version you can use the following structure:

DROP TABLE IF EXISTS `tbl_user`;

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`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

/*Data for the table `tbl_user` */

insert  into `tbl_user`(`user_id`,`user_name`,`user_email`,`user_password`) values 
(2,'Soumitra Roy','soumitra@email.com','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`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

insert  into `tbl_user`(`user_id`,`user_name`,`user_email`,`user_password`) values 
(2,'Soumitra Roy','soumitra@email.com','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 main.py or main.py, your server will start on default port 5000. If you want to change the port then you can change the line app.run() to app.run(port=50001), 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

Download

2 thoughts on “Python Flask Login and Logout Example

  1. it is getting imported from other module so keep py file same as it has been told app.py db_config.py, main.py same as it is

  2. im getting error in db_config.py 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 *