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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read