Bucketlist With Flask and MySQL
Bucketlist With Flask and MySQL
Sign In
Python
Web App
App Development
HTML
MySQL
CSS
JavaScript
This post is part of a series called Creating a Web App From Scratch Using Python Flask and
MySQL.
Creating a Web App From Scratch Using Python Flask and MySQL: Part 2
In this series, we'll be using Python, Flaskand MySQLto create a simple web
application from scratch. It will be a simple bucket list application where users
can register, sign in and create their bucket list.
This tutorial assumes that youhave some basic knowledge of the Python
programming language. We'll be using Flask , a Python web application
framework, to create our application, with MySQL as the back end.
If you need to brush up on your Python skills, try the Introduction to Python
course, which gives you a solid foundation in the language for just $5.
FlaskisamicroframeworkforPythonbasedonWerkzeug,
Jinja2andgoodintentions.
When we think about Python, the de facto framework that comes to our mind is
the Django framework. But from a Python beginner's perspective, Flask is
easier to get started with,when compared toDjango.
Setting Up Flask
Setting up Flask is pretty simple and quick. With pip package manager, all we
need to do is:
1
Once you're done with installing Flask, create a folder called FlaskApp .
Navigate to the FlaskApp folder and create a le called app.py . Import the
flask module and create an app using Flask as shown:
1
2
Now dene the basic route / and its corresponding request handler:
1
2
3
@app.route("/")
def main():
return "Welcome!"
Next, check if the executed le is themain program and run the app:
1
2
if __name__ == "__main__":
app.run()
python app.py
First, when the application runs we should show a home page with the latest
bucket list items added by users. So let's add our home page to our application
folder.
Flask looks for template les inside the templates folder. So navigate to the
PythonApp folder and create a folder called templates . Inside templates ,
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask Bucket List App</title>
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css
</head>
<body>
<div class="container">
<div class="header">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation" class="active"><a href="#"
</li>
<li role="presentation"><a href="#">Sign In</a>
</li>
<li role="presentation"><a href="showSignUp">Sign Up</
</li>
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<div class="jumbotron">
<h1>Bucket List App</h1>
<p class="lead"></p>
<p><a class="btn btn-lg btn-success" href="showSignUp" role
</p>
</div>
<h4>Bucket List</h4>
<p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis c
<h4>Bucket List</h4>
<p>Maecenas sed diam eget risus varius blandit sit amet non magna.</
</div>
<div class="col-lg-6">
<h4>Bucket List</h4>
<p>Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis
<h4>Bucket List</h4>
<p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis c
<h4>Bucket List</h4>
<p>Maecenas sed diam eget risus varius blandit sit amet non magna.</
</div>
</div>
<footer class="footer">
<p>© Company 2015</p>
</footer>
</div>
67
68
69
70
</div>
</body>
</html>
Open up app.py and import render_template , which we'll use to render the
template les.
1
def main():
return render_template('index.html')
Save the changes and restart the server. Point your browser to
http://localhost:5000/ and you should have the below screen:
We'll be using MySQL as the back end. So log into MySQL from the command
line, or if you prefer a GUI like MySQL work bench, you can use that too. First,
create a database called BucketList . From the command line:
1
mysql -u <username> -p
Enter the required password and when logged in, execute the following
command to create the database:
1
Once the database has been created, create a table called tbl_user as
shown:
1
2
3
4
5
6
We'll be using Stored procedures for our Python application to interact with
the MySQL database. So, once the table tbl_user has been created, create a
stored procedure called sp_createUser to sign up a user.
When creating a stored procedure to create a user in the tbl_user table, rst
we need to check if a user with the same username already exists. If it exists
we need to throw an error to the user, otherwise we'll create the user in the user
table. Here is how the stored procedure sp_createUser would look:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_createUser`(
IN p_name VARCHAR(20),
IN p_username VARCHAR(20),
IN p_password VARCHAR(20)
)
BEGIN
if ( select exists (select 1 from tbl_user where user_username = p_username) )
ELSE
END IF;
END$$
DELIMITER ;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask Bucket List App</title>
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css
<link href="../static/signup.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation" ><a href="main">Home</a></li>
<li role="presentation"><a href="#">Sign In</a></li>
<li role="presentation" class="active"><a href="#">Sign Up</
</ul>
</nav>
<h3 class="text-muted">Python Flask App</h3>
</div>
<div class="jumbotron">
<h1>Bucket List App</h1>
<form class="form-signin">
<label for="inputName" class="sr-only">Name</label>
<input type="name" name="inputName" id="inputName" class="form-control"
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="inputEmail" id="inputEmail" class="form-control"
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="inputPassword" id="inputPassword"
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<footer class="footer">
<p>© Company 2015</p>
</footer>
</div>
</body>
</html>
Also add the following CSS as signup.css to the static folder inside
PythonApp .
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
body {
padding-top: 40px;
padding-bottom: 40px;
}
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
position: relative;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
In app.py add another method called showSignUp to render the signup page
once a request comes to /showSignUp :
1
2
3
@app.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
Save the changes and restart the server. Click on the Sign Up button on the
home page and you should have the signup page as shown:
1
2
3
@app.route('/signUp')
def signUp():
# create user code will be here !!
We'll be using jQuery AJAX to post our signup data to the signUp method, so
we'll specify the method in the route denition.
1
2
3
@app.route('/signUp',methods=['POST'])
def signUp():
# create user code will be here !!
In order to read the posted values we need to import request from Flask.
1
@app.route('/signUp',methods=['POST'])
def signUp():
Once the values are read, we'll simply check if they are valid and for the time
being let's just return a simple message:
01
02
@app.route('/signUp',methods=['POST'])
def signUp():
03
04
05
06
07
08
09
10
11
12
13
Also import json from Flask, since we are using it in the above code to return
json data.
1
$(function() {
$('#btnSignUp').click(function() {
$.ajax({
url: '/signUp',
data: $('form').serialize(),
type: 'POST',
07
08
09
10
11
12
13
14
15
16
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
});
Save all the changes and restart the server. From the Sign Up page, ll in the
details and click Sign Up. Check the browser console and you should have the
below message:
1
app = Flask(__name__)
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'jay'
app.config['MYSQL_DATABASE_PASSWORD'] = 'jay'
app.config['MYSQL_DATABASE_DB'] = 'BucketList'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
conn = mysql.connect()
Once the connection is created, we'll require a cursor to query our stored
procedure. So, using conn connection, create a cursor.
1
cursor = conn.cursor()
Before calling the create user stored procedure, let's make our password salted
using a helper provided by Werkzeug. Import the module into app.py :
from werkzeug import generate_password_hash, check_password_hash
_hashed_password = generate_password_hash(_password)
cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
If the procedure is executed successfully, then we'll commit the changes and
return the success message.
1
2
3
4
5
6
7
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return json.dumps({'message':'User created successfully !'})
else:
return json.dumps({'error':str(data[0])})
Save the changes and restart the server. Go to the signup page and enter the
name , email address and password and click the Sign Up button. On
Wrapping It Up
In this tutorial, we saw how to get started with creating a web application using
Python Flask , MySQL and the Flask-MySQL extension. We created and