Python Login and Logout Example


The tutorial, Python login and logout example will show you how to login and logout a user using session in Python 3. We 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.


Have Python installed in Windows (or Unix)

Pyhton version and Packages

I am using Python 3.6.6 version

MySQL Database 5.6

Flask module

Example with Source Code

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 we import the flask module. Notice how we create flask instance. Here we 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. We create the below Python script to setup the MySQL database configurations for connecting to database. We need to configure database connection with flask module and that’s why we 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'] = ''
app.config['MYSQL_DATABASE_DB'] = 'roytuts'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

Step 3. Next we 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:

We have used login.html page for log in to the system but for home or index page we 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 we 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


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','[email protected]','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, 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

download source code

Thanks for reading.

Related posts

4 Thoughts to “Python Login and Logout Example”

  1. vinod

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

  2. I am from Indonesia, sorry if my English is bad.
    I feel helped from the tutorial
    I hope there is also a python login and logout example tutorial using Rest API, I am waiting for your next tutorial, please let me know by email, thank you

Leave a Comment