Profile Application using Python Flask and MySQL
Last Updated :
19 Apr, 2023
A framework is a code library that makes a developer's life easier when building web applications by providing reusable code for common operations. There are a number of frameworks for Python, including Flask, Tornado, Pyramid, and Django. Flask is a lightweight web application framework. It is classified as a micro-framework because it does not require particular tools or libraries. Side tabs are used for single-page web applications or to display different contents.
Pre-requisite:Â
- Knowledge of Python,Â
- MySQL Workbench, andÂ
- basics of Flask Framework.Â
Profile Application using Flask
Working with MySQL Workbench
Step-1: Install MySQL workbench. Link to install : https://dev.mysql.com/downloads/workbench/ Know more about it : https://www.mysql.com/products/workbench/ Step-2: Install 'mysqlbd' module in your venv.
pip install flask-mysqldb
Step 3: Open MySQL workbench.Â
Step 4: Write the following code. The above SQL statement will create our database geekprofile with the table accounts.Â
Step-5: Execute the query. 
Creating ProjectÂ
Step 1: Create an environment, and install Flask
Step 2: Create an empty folder 'geeksprofile'.Â
Step 3: Now open your code editor and open this 'geeksprofile' folder.Â
Step 4: Create 'app.py' folder and write the code given below.Â
Python3
# Store this code in 'app.py' file
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
app = Flask(__name__)
app.secret_key = 'your secret key'
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'geekprofile'
mysql = MySQL(app)
@app.route('/')
@app.route('/login', methods=['GET', 'POST'])
def login():
msg = ''
if request.method == 'POST' and 'username' in
request.form and 'password' in request.form:
username = request.form['username']
password = request.form['password']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(
'SELECT * FROM accounts WHERE username = % s \
AND password = % s', (username, password, ))
account = cursor.fetchone()
if account:
session['loggedin'] = True
session['id'] = account['id']
session['username'] = account['username']
msg = 'Logged in successfully !'
return render_template('index.html', msg=msg)
else:
msg = 'Incorrect username / password !'
return render_template('login.html', msg=msg)
@app.route('/logout')
def logout():
session.pop('loggedin', None)
session.pop('id', None)
session.pop('username', None)
return redirect(url_for('login'))
@app.route('/register', methods=['GET', 'POST'])
def register():
msg = ''
if request.method == 'POST' and 'username' in
request.form and 'password' in request.form and
'email' in request.form and 'address' in
request.form and 'city' in request.form and
'country' in request.form and 'postalcode'
in request.form and 'organisation' in request.form:
username = request.form['username']
password = request.form['password']
email = request.form['email']
organisation = request.form['organisation']
address = request.form['address']
city = request.form['city']
state = request.form['state']
country = request.form['country']
postalcode = request.form['postalcode']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(
'SELECT * FROM accounts WHERE username = % s', (username, ))
account = cursor.fetchone()
if account:
msg = 'Account already exists !'
elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
msg = 'Invalid email address !'
elif not re.match(r'[A-Za-z0-9]+', username):
msg = 'name must contain only characters and numbers !'
else:
cursor.execute('INSERT INTO accounts VALUES \
(NULL, % s, % s, % s, % s, % s, % s, % s, % s, % s)',
(username, password, email,
organisation, address, city,
state, country, postalcode, ))
mysql.connection.commit()
msg = 'You have successfully registered !'
elif request.method == 'POST':
msg = 'Please fill out the form !'
return render_template('register.html', msg=msg)
@app.route("/index")
def index():
if 'loggedin' in session:
return render_template("index.html")
return redirect(url_for('login'))
@app.route("/display")
def display():
if 'loggedin' in session:
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE id = % s',
(session['id'], ))
account = cursor.fetchone()
return render_template("display.html", account=account)
return redirect(url_for('login'))
@app.route("/update", methods=['GET', 'POST'])
def update():
msg = ''
if 'loggedin' in session:
if request.method == 'POST' and 'username' in request.form
and 'password' in request.form and 'email' in request.form and
'address' in request.form and 'city' in request.form and 'country'
in request.form and 'postalcode' in request.form and
'organisation' in request.form:
username = request.form['username']
password = request.form['password']
email = request.form['email']
organisation = request.form['organisation']
address = request.form['address']
city = request.form['city']
state = request.form['state']
country = request.form['country']
postalcode = request.form['postalcode']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(
'SELECT * FROM accounts WHERE username = % s',
(username, ))
account = cursor.fetchone()
if account:
msg = 'Account already exists !'
elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
msg = 'Invalid email address !'
elif not re.match(r'[A-Za-z0-9]+', username):
msg = 'name must contain only characters and numbers !'
else:
cursor.execute('UPDATE accounts SET username =% s,\
password =% s, email =% s, organisation =% s, \
address =% s, city =% s, state =% s, \
country =% s, postalcode =% s WHERE id =% s', (
username, password, email, organisation,
address, city, state, country, postalcode,
(session['id'], ), ))
mysql.connection.commit()
msg = 'You have successfully updated !'
elif request.method == 'POST':
msg = 'Please fill out the form !'
return render_template("update.html", msg=msg)
return redirect(url_for('login'))
if __name__ == "__main__":
app.run(host="localhost", port=int("5000"))
Step 5: Create the folder 'templates'. create the files 'index.html', 'display.html', 'update.html', 'login.html', and 'register.html' inside the 'templates' folder.Â
Step 6: Open the 'login.html' file and write the code given below. In 'login.html', we have two fields i.e. username and password. When a user enters the correct username and password, it will route you to the index page otherwise 'Incorrect username/password' is displayed.Â
html
<!--Store this code in 'login.html' file inside the 'templates' folder-->
<html>
<head>
<meta charset="UTF-8">
<title> Login </title>
<link rel="stylesheet" href="../static/style.css">
</head>
<body>
<div class="logincontent" align="center">
<div class="logintop">
<h1>Login</h1>
</div></br></br></br></br>
<div class="loginbottom">
<form action="{{ url_for('login')}}" method="post" autocomplete="off">
<div class="msg">{{ msg }}</div>
<input type="text" name="username" placeholder="Enter Your Username" class="textbox" id="username" required></br></br>
<input type="password" name="password" placeholder="Enter Your Password" class="textbox" id="password" required></br></br></br>
<input type="submit" class="btn" value="Login">
</form></br></br>
<p class="worddark">New to this page? <a class="worddark" href="{{ url_for('register')}}">Register here</a></p>
</div>
</div>
</body>
</html>
Step 7: Open 'register.html' file and write the code given below. In 'register.html', we have nine fields i.e. username, password, email, organisation, address, city, state, country, postal code. When user enters all the information, it stored the data in the database and 'Registration successful' is displayed.Â
html
<!--Store this code in 'register.html' file inside the 'templates' folder-->
<html>
<head>
<meta charset="UTF-8">
<title> register </title>
<link rel="stylesheet" href="../static/style.css">
</head>
<body>
<div class="registercontent" align="center">
<div class="registertop">
<h1>Register</h1>
</div></br></br>
<div class="registerbottom">
<form action="{{ url_for('register')}}" method="post" autocomplete="off">
<div class="msg">{{ msg }}</div>
<input type="text" name="username" placeholder="Enter Your Username" class="textbox" id="username" required></br></br>
<input type="password" name="password" placeholder="Enter Your Password" class="textbox" id="password" required></br></br>
<input type="email" name="email" placeholder="Enter Your Email ID" class="textbox" id="email" required></br></br>
<input type="text" name="organisation" placeholder="Enter Your Organisation" class="textbox" id="organisation" required></br></br>
<input type="text" name="address" placeholder="Enter Your Address" class="textbox" id="address" required></br></br>
<input type="text" name="city" placeholder="Enter Your City" class="textbox" id="city" required></br></br>
<input type="text" name="state" placeholder="Enter Your State" class="textbox" id="state" required></br></br>
<input type="text" name="country" placeholder="Enter Your Country" class="textbox" id="country" required></br></br>
<input type="text" name="postalcode" placeholder="Enter Your Postal Code" class="textbox" id="postalcode" required></br></br>
<input type="submit" class="btn" value="Register">
</form>
<p class="worddark">Already have account? <a class="worddark" href="{{ url_for('login')}}">Login here</a></p>
</div>
</div>
</body>
</html>
Step 8: Open 'index.html' file and write the code given below. When a user logs in successfully, this page is displayed, and 'Logged in successful!' is displayed.Â
html
<!--Store this code in 'index.html' file inside the 'templates' folder-->
<html lang="en">
<head>
<title>index</title>
<link rel="stylesheet" href="../static/style.css">
</head>
<body bgcolor="#e6ffee">
<div class="one">
<div class="two">
<h1>Side Bar</h1>
<ul>
<li class="active"><a href="{{url_for('index')}}">Index</a></li>
<li><a href="{{url_for('display')}}">Display</a></li>
<li><a href="{{url_for('update')}}">Update</a></li>
<li><a href="{{url_for('logout')}}">Log out</a></li>
</ul>
</div>
<div class="content" align="center">
<div class="topbar">
<h2>Welcome!! You are in Index Page!! </h2>
</div></br></br>
<div class="contentbar">
<div class="msg">{{ msg }}</div>
</div>
</div>
</div>
</body>
</html>
Step 9: Open 'display.html' file and write the code given below. Here, the user information stored in database are displayed.Â
html
<!--Store this code in 'display.html' file inside the 'templates' folder-->
<html lang="en">
<head>
<title>display</title>
<link rel="stylesheet" href="../static/style.css">
</head>
<body bgcolor="#e6ffee">
<div class="one">
<div class="two">
<h1>Side Bar</h1>
<ul>
<li><a href="{{url_for('index')}}">Index</a></li>
<li class="active"><a href="{{url_for('display')}}">Display</a></li>
<li><a href="{{url_for('update')}}">Update</a></li>
<li><a href="{{url_for('logout')}}">Log out</a></li>
</ul>
</div>
<div class="content" align="center">
<div class="topbar">
<h2>Welcome!! You are in Display Page!! </h2>
</div> </br>
<div class="contentbar">
<h1>Your Details</h1> </br>
{% block content %}
<div class="border">
<table class="worddark"></br></br></br></br>
<tr>
<td>Username:</td>
<td>{{ account['username'] }}</td>
</tr>
<tr>
<td>Password:</td>
<td>{{ account['password'] }}</td>
</tr>
<tr>
<td>Email ID:</td>
<td>{{ account['email'] }}</td>
</tr>
<tr>
<td>Organisation:</td>
<td>{{ account['organisation'] }}</td>
</tr>
<tr>
<td>Address:</td>
<td>{{ account['address'] }}</td>
</tr>
<tr>
<td>City:</td>
<td>{{ account['city'] }}</td>
</tr>
<tr>
<td>State:</td>
<td>{{ account['state'] }}</td>
</tr>
<tr>
<td>Country:</td>
<td>{{ account['country'] }}</td>
</tr>
<tr>
<td>Postal code:</td>
<td>{{ account['postalcode'] }}</td>
</tr>
</table>
</div>
{% endblock %}
</div>
</div>
</div>
</body>
</html>
Step 10: Open 'update.html' file and write the code given below. The user can update his/her data which also updates the database.Â
html
<!--Store this code in 'update.html' file inside the 'templates' folder-->
<html lang="en">
<head>
<title>update</title>
<link rel="stylesheet" href="../static/style.css">
</head>
<body bgcolor="#e6ffee">
<div class="one">
<div class="two">
<h1>Side Bar</h1>
<ul>
<li><a href="{{url_for('index')}}">Index</a></li>
<li><a href="{{url_for('display')}}">Display</a></li>
<li class="active"><a href="{{url_for('update')}}">Update</a></li>
<li><a href="{{url_for('logout')}}">Log out</a></li>
</ul>
</div>
<div class="content" align="center">
<div class="topbar">
<h2>Welcome!! You are in Update Page!! </h2>
</div></br></br>
<div class="contentbar">
<h1>Fill Your Details to Update</h1></br>
<form action="{{ url_for('update') }}" method="post" autocomplete="off">
<div class="msg">{{ msg }}</div>
<input type="text" name="username" placeholder="Enter Your Username" class="textbox" id="username" required></br></br>
<input type="password" name="password" placeholder="Enter Your Password" class="textbox" id="password" required></br></br>
<input type="email" name="email" placeholder="Enter Your Email ID" class="textbox" id="email" required></br></br>
<input type="text" name="organisation" placeholder="Enter Your Organisation" class="textbox" id="organisation" required></br></br>
<input type="text" name="address" placeholder="Enter Your Address" class="textbox" id="address" required></br></br>
<input type="text" name="city" placeholder="Enter Your City" class="textbox" id="city" required></br></br>
<input type="text" name="state" placeholder="Enter Your State" class="textbox" id="state" required></br></br>
<input type="text" name="country" placeholder="Enter Your Country" class="textbox" id="country" required></br></br>
<input type="text" name="postalcode" placeholder="Enter Your Postal Code" class="textbox" id="postalcode" required></br></br>
<input type="submit" class="btn" value="Update">
</form>
</div>
</div>
</div>
</body>
</html>
Step 11: Create the folder 'static'. create the file 'style.css' inside the 'static' folder and paste the given CSS code.Â
css
/*Store this code in 'style.css' file inside the 'static' folder*/
.logincontent{
margin: 0 auto;
height: 500px;
width: 400px;
background-color: #e6ffee;
border-radius: 10px;
}
.registercontent{
margin: 0 auto;
height: 720px;
width: 400px;
background-color: #e6ffee;
border-radius: 10px;
}
.logintop{
height: 60px;
width: 400px;
background-color: #009933;
color: #ffffff;
}
.registertop{
height: 60px;
width: 400px;
background-color: #009933;
color: #ffffff;
}
.textbox{
padding: 10px 40px;
background-color: #009933;
border-radius: 10px;
}
::placeholder {
color: #FFFFFF;
opacity: 1;
font-style: oblique;
font-weight: bold;
}
.btn {
padding: 10px 40px;
background-color: #009933;
color: #FFFFFF;
font-style: oblique;
font-weight: bold;
border-radius: 10px;
}
.worddark{
color: #009933;
font-style: oblique;
font-weight: bold;
}
.wordlight{
color: #FFFFFF;
font-style: oblique;
font-weight: bold;
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
text-decoration: none;
font-family: 'Josefin Sans', sans-serif;
}
.one{
display: flex;
position: relative;
}
.one .two{
width: 225px;
height: 100%;
background: #009933;
padding: 30px 0px;
position: fixed;
}
.one .two h1{
color: #fff;
text-transform: uppercase;
text-align: center;
margin-bottom: 30px;
font-style: oblique;
font-weight: bold;
}
.one .two h2{
color: #fff;
text-align: center;
}
.one .two .active{
background: #0a8032;
}
.one .two ul li{
text-align: center;
padding: 15px;
border-bottom: 0.1px solid white;
border-top: 0.1px solid white;
}
.one .two ul li a{
color: #ffffff;
display: block;
}
.one .two ul li a .side{
width: 25px;
align:center;
}
.one .content{
width: 100%;
margin-left: 200px;
}
.one .content .topbar{
text-align: center;
padding: 20px;
background: #00b33c;
color: white;
}
.one .content .contentbar{
margin: auto;
}
.one .content .contentbar h1{
color: #11a844;
text-align: center;
font-style: oblique;
font-weight: bold;
}
Step 12: The project structure will look like this.Â
 Run the ProjectÂ
Step-1: Run the server.Â
Step-2: Browse the URL 'localhost:5000'.Â
Step-3: The output web page will be displayed.Â
Testing of the ApplicationÂ
Step-1: If you are new user, go to sign up page and fill the details.Â
Step-2: After registration, go to login page. Enter your username and password and sign in.Â
Step-3: If your login is successful, you will be moved to index page and your name will be displayed.Â
Step-4: You can view your profile details in display page and also you can update your details in update page.Â
Output: Login page:Â
Â
 Register page:Â
Â
 If login is successful, Index Page:
Update Page:
Before updation, Display page:
After updation, Display page:
Database - Before update:Â
Â
 Database - After update:Â
Â
Similar Reads
How To Use Web Forms in a Flask Application
A web framework called Flask provides modules for making straightforward web applications in Python. It was created using the WSGI tools and the Jinja2 template engine. An example of a micro-framework is Flask. Python web application development follows the WSGI standard, also referred to as web ser
5 min read
Flask NEWS Application Using Newsapi
In this article, we will create a News Web Application using Flask and NewsAPI. The web page will display top headlines and a search bar where the user can enter a query, after processing the query, the webpage will display all relevant articles (up to a max of 100 headlines). We will create a simpl
7 min read
How to Run a Flask Application
After successfully creating a Flask app, we can run it on the development server using the Flask CLI or by running the Python script. Simply execute one of the following commands in the terminal:flask --app app_name runpython app_nameFile StructureHere, we are using the following folder and file.Dem
4 min read
CRUD Operation in Python using MySQL
In this article, we will be seeing how to perform CRUD (CREATE, READ, UPDATE and DELETE) operations in Python using MySQL. For this, we will be using the Python MySQL connector. For MySQL, we have used Visual Studio Code for python. Before beginning we need to install the MySQL connector with the co
6 min read
Login and Registration Project in Flask using MySQL
Creating a user authentication system is a fundamental part of web applications. This guide will help you build a Login and Registration system using Flask and MySQL.Prerequisites - Basic knowledge of Python, MySQL Workbench, and Flask.To learn how to build login and registration in Flask, let's cre
6 min read
Grant MySQL table and column permissions using Python
MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a w
2 min read
Todo list app using Flask | Python
There are many frameworks that allow building your webpage using Python, like Django, flask, etc. Flask is a web application framework written in Python. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. Its modules and libraries that help the developer to writ
3 min read
Load Balancing Flask Application using Nginx and Docker
Load balancing means efficiently distributing the incoming traffic to different server instances. Nginx is open-source software that can be used to apply load balancing to backend systems. Nginx also can be serve services such as reverse proxy, caching, web server, etc.Docker is a tool that gives a
4 min read
Create a Weather app using Flask | Python
Prerequisite : Flask installation Flask is a lightweight framework written in Python. It is lightweight because it does not require particular tools or libraries and allow rapid web development. today we will create a weather app using flask as a web framework. this weather web app will provide curr
2 min read
Connect to MySQL using PyMySQL in Python
In this article, we will discuss how to connect to the MySQL database remotely or locally using Python. In below process, we will use PyMySQL module of Python to connect our database. What is PyMySQL? This package contains a pure-Python MySQL client library, based on PEP 249. Requirements : MySQL Se
2 min read