Lab Building Simple Shopping Cart Using Python, Flask, MySQL
Lab Building Simple Shopping Cart Using Python, Flask, MySQL
MySQL
Introduction
We will see here how to build a simple shopping cart using Python, Flask, MySQL. This
shopping cart is very simple and it does not have checkout option, payment option. This is
about to display products in an online shopping portal, add item to cart, remove item from
cart and remove all items from cart at once or empty cart.
Lab Objective
After completing this lab, you will be able to:
Prerequisites
Python 3.7.4, MySQL 8.0.17, Flask 1.1.1, Windows 10
Need flask_table and MySQL modules : check tutorial for installation these two
modules
Lab Procedure
A. Creating Project Directory
First step is to create a project root directory under which we will put all our required
files for the project.
Let’s say we are going to create a project root directory “shopcart”. We may not
mention the project root directory in subsequent sections and we will assume that we
are talking with respect to the project’s root directory.
C. Dumping Data
We will test our application when we finish with coding, so dump some data
into product table.
INSERT INTO `product` (`id`, `name`, `code`, `image`, `price`) VALUES
D. Configuring Flask
Create the below app.py script(py is the extension to indicate Python script) where we
import the flask module. This file should be created under the project root directory.
Notice how we create flask instance. We have configured a secret key, which is
required for your application’s session.
from flask import Flask
app = Flask(__name__)
app.secret_key = "secret key"
E. Database Configuration
We create the below db_config.py Python script under project root directory 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
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'roytuts'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
F. Configuring URLs
Next we will create main.py script that will define all URIs or Action paths for
performing certain operations used for cart or to fetch all products from the database.
It will connect to MySQL database server and query the database to read all products
from the database table.
In this script we perform certain operations with user interaction.
We first import required modules into the script. We then define the end-point / for
displaying a view where user will see all the products.
Next we need to validate user input data and save those input data into into cart, i.e.,
flask session. So we define another end-point /add. Here we fetch the data based on
product’s code from MySQL database and put into session against unique product
keys.
We use http method GET for displaying view and POST method for sending data to
server side. By default http method is GET if you do not specify http method.
We use render_template function from flask to show the view.
Initially when there is no product or item in the cart then you won’t see any item or
product in the cart on home page or products page.
If you add product to cart from Add to Cart link shown on each product then you will
see product gets added and displayed into the cart.
We define /empty endpoint to clear all items from the cart.
Next we define /delete/<string:code> end-point where user deletes product one
by one from the cart.
import pymysql
@app.route('/add', methods=['POST'])
def add_product_to_cart():
cursor = None
try:
_quantity = int(request.form['quantity'])
_code = request.form['code']
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
row = cursor.fetchone()
all_total_quantity = 0
session.modified = True
if 'cart_item' in session:
if row['code'] in session['cart_item']:
if row['code'] == key:
#session.modified = True
#session['cart_item'][key]['quantity'] = 0
old_quantity = session['cart_item'][key]['quantity']
session['cart_item'][key]['quantity'] = total_quantity
session['cart_item'][key]['total_price'] = total_quantity *
row['price']
else:
individual_quantity = int(session['cart_item'][key]['quantity'])
individual_price = float(session['cart_item'][key]['total_price'])
else:
session['cart_item'] = itemArray
session['all_total_quantity'] = all_total_quantity
session['all_total_price'] = all_total_price
return redirect(url_for('.products'))
else:
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/')
def products():
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
rows = cursor.fetchall()
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/empty')
def empty_cart():
try:
session.clear()
return redirect(url_for('.products'))
except Exception as e:
print(e)
@app.route('/delete/<string:code>')
def delete_product(code):
try:
all_total_price = 0
all_total_quantity = 0
session.modified = True
if item[0] == code:
session['cart_item'].pop(item[0], None)
if 'cart_item' in session:
individual_quantity =
int(session['cart_item'][key]['quantity'])
individual_price =
float(session['cart_item'][key]['total_price'])
all_total_quantity =
all_total_quantity + individual_quantity
all_total_price =
all_total_price + individual_price
break
if all_total_quantity == 0:
session.clear()
else:
session['all_total_quantity'] = all_total_quantity
session['all_total_price'] = all_total_price
#return redirect('/')
return redirect(url_for('.products'))
except Exception as e:
print(e)
if __name__ == "__main__":
app.run()
<html>
<head>
</head>
<body>
<div>
{% if messages %}
<ul class=flashes>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</div>
<div id="shopping-cart">
{% if 'cart_item' in session %}
<a id="btnEmpty"
href="{{ url_for('.empty_cart') }}">Empty Cart</a>
<tbody>
<tr>
<th style="text-align:left;">Name</th>
<th style="text-align:left;">Code</th>
</tr>
<td style="text-align:center;">
</a>
</td>
</tr>
{% endfor %}
<tr>
<td></td>
</tr>
</tbody>
</table>
{% else: %}
{% endif %}
</div>
<div id="product-grid">
<div class="txt-heading">Products</div>
<div class="product-item">
<div class="product-image"><img
src="/static/images/{{ product.image }}"></div>
<div class="product-tile-footer">
<div class="product-price">₹
{{ product.price }}</div>
<div class="cart-action">
</div>
</div>
</form>
</div>
{% endfor %}
</div>
</body>
</html>
Cart Items