Login with MySQL in Flask and Python | Website in Python

Step by Step Guide to Login with MySQL using Flask and Python.
Hello friends how are you, Today in this blog i will teach you how you can login  with MySQL using Python and Flask. If you are making any kind of project on any kind of platform then Login is the most used form in any kind of project for example Login is used for Admin , Customer, Students etc as per the requirements of projects.

Request: If you don't know how to create website in Python using Flask then first visit the below links

Flask is a popular Web Framework which is used to create a website in python. We can also create a website in Python using Django Web Framework, in the upcoming post i will create a complete post on creating a website using Python and Django Framework.

In this post i will explain step by step the following topics:

1.Create Database in MySQL
2.Create Table in MySQL
3.Insert Data in MySQL
4.Create Login Form in HTML
5.Create Python file for Login code

Let's Start

Create Database in MySQL

Open MySQL in your system and create a database with name "ProjectReporting", If you want to create database using SQL Query then copy the below query and execute this to create database. Following is the query for creating database in MySQL.

CREATE DATABASE ProjectReporting

Create a Table

Now create a table wit name "ADMIN" with three fields [ADMIN_ID,USERNAME,PASSWORD] inside the database "ProjectReporting". If you don't know how to create table inside database then You just need to copy the below query to create table in MySQL. Following is the query to create a table "ADMIN" in MySQL.

CREATE TABLE ADMIN (
    ADMIN_ID int NOT NULL AUTO_INCREMENT,
    USERNAME varchar(255) NOT NULL,
    PASSWORD varchar(255),
    PRIMARY KEY (ADMIN_ID)
);
  
Insert Data in MySQL
Now we have created a database "ProjectReporting" in MySQL and table "ADMIN" inside the database. After that its time to insert some data in the table so that we can perform login operation from website with MySQL. Following is the syntax to insert data in table.

INSERT INTO TABLE_NAME (column1, column2,column3,...columnN)
VALUES (value1, value2, value3,...valueN);

and following is the query to insert data in table.

INSERT INTO ADMIN(USERNAME, PASSWORD, EMAIL) 
VALUES ('admin', 'admin123'),
 ('krazy', 'programmer'')

The above query will insert two rows in table  of database, After doing this we have two records in our database, Have a look  on records of database.


Create Project and HTML file 

Now open Pycharm , create a project with name "Flask Project", create  two folders with name "static" and "templates" inside project, Create another folder with name "image" inside folder "static" and store an image and rename the image with "login.jpg" , Now create a HTML file with name "admin.html" inside the folder "templates".

Here i have explained "Create Project and HTML file " in very short because i have already made a complete post on it so if you are not able able to understand then visit the below link.
  

Now open "admin.html" file and type the below code or you can copy the given code.

<html>
<head>
    <title>KrazyProgrammer</title>
<style>

a{
color:white;
background-color:#FF3399;
padding:5px 15px 5px 15px;
text-decoration:none;
border-radius:20px;
display: block;
width: 120px;
}
.login-dark
{
background-color:rgb(30,40,51);
text-align:center;
padding:20px;
width:300px;
height:300px;
border-radius:5px;
}

* {box-sizing: border-box;}
body {font-family: Verdana, sans-serif;}
.mySlides {display: none;}
img {vertical-align: middle;}


</style>
</head>
<body style="background-color:rgb(6,23,58)">
{{error}}
<table border="0" width="100%" height="10%" bgcolor="#000000" style="position: absolute; top: 0; bottom: 0; left: 0; right: 0;border-bottom:1px dotted white;">
<tr>
<td style="color:#ffffff;font-size:50px;text-shadow:2px 2px 2px red">Project Reporting</td>
<td width="10%" align="center"> <a href="index">Home</a></td>
<td width="10%" align="center"> <a href="about">About</a></td>
<td width="10%" align="center"> <a href="projectreg">Registration</a></td>
<td width="10%" align="center"> <a href="projectlist">Project List</a></td>
<td width="10%" align="center"> <a href="admin">Admin</a></td>
</tr>
</table><br><br><br><br><br><br><br>

<table border="0" bgcolor="#666633" style="box-shadow:1px 1px 10px white" width="70%" height="70%" align="center">
<tr>
<td align="center"  width="50%">

<img src="static/image/login.jpg" style="width:500px;height:300px;border-radius:5px">
</td>
<td style="background-position:center center" align="center">
 <div class="login-dark">
        <form method="post" action="{{ url_for('admin') }}">
            {{msg}}
            <h2 class="sr-only" style="color:#6666ff">Login Form</h2>
            <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
            <div class="form-group" style="padding:10px">
			<input class="form-control" style="padding:5px" type="text" name="uname" placeholder="Username" required>
			</div>
            <div class="form-group" style="padding:10px">
			<input class="form-control" style="padding:5px" type="password" name="pwd" placeholder="Password" required></div>
            <div class="form-group" style="padding:10px">
			<button class="btn btn-primary btn-block" style="background-color:rgb(33,74,128);width:169px;border:none;color:white;padding:5px 10px 5px 10px;border-radius:2px;" type="submit">Log In</button></div>
			</form>
    </div>
</td>
</tr>
<tr style="background-color:black;color:white;height:25px">
<td colspan="2"><marquee behavior="alternate">
Welcome of You in my Project.
</marquee></td>
</tr>
</table>
</body>
</html>

Create Python File

Now we need to create a Python file to execute this HTML file on web. So create a python file inside your project with name  "app.py"

Now open python file and i am giving you the complete code of this file you just type the below code or you can copy this code for your personal use.

from flask import Flask, render_template, request, redirect, url_for, session,flash
from flask_mysqldb import MySQL
import MySQLdb.cursors
app = Flask(__name__)
#code for connection with MySQL
#MySQL host
app.config['MYSQL_HOST'] = 'localhost'
#MySQL username
app.config['MYSQL_USER'] = 'root'
#MySQL password
app.config['MYSQL_PASSWORD'] = ''
#MySQL Database name
app.config['MYSQL_DB'] = 'projectreporting'

mysql = MySQL(app)
@app.route('/')
@app.route('/admin',methods=['GET','POST'])
def admin():
    msg=''
    if request.method=='POST' and 'uname' in request.form and 'pwd' in request.form:
        un=request.form['uname']
        pwd=request.form['pwd']
        cur=mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("select * from admin where username=%s and password=%s",(un,pwd,))
        acount=cur.fetchone()
        if acount:
            msg='Logged in Successfully'
            #After login if you want to call a new page then use the below line
            #return render_template("index.html")
        else:
            msg='Wrong username or password!'
    return render_template("admin.html",msg=msg)
if __name__ == '__main__':
    app.run(port=5000,debug=True)

Run Python Code

After doing all these things now you have to run the python code and look on to the console screen which is below the python code or editor, for better understanding see the below screenshot


when you will paste this URL in any browser then you will get output screen like below


Login with wrong username or password
When you will type username and password in the login form and  that username or password is not stored in the database then you will get a message "Wrong username or password!" 




Login with Success

When you will type username and password in the login form and  that username or password is stored in the database then you will get a message "Logged in Successfully" 


I hope now you can Login with MySQL in Python using Flask Web Framework. If you have any doubt regarding this post  or you want something more in this post then let me know by comment below i will work on it definitely.

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. 

If you like my post then share it with your friends. Thanks😊Happy Coding.

Post a Comment

1 Comments