Building E-Commerce Features with Flask ①
CREATED: 2024 / 04 / 05 Fri
UPDATED: 2024 / 04 / 06 Sat
Why Flask?
I’m using Flask simply because I’ve been playing with it as a hobby recently — no deep reason. Whatever framework you use, the core ideas don’t really change.
The goal is a simple EC (e-commerce) site. For actual purchase functionality, integrating something like Stripe would work well. I use Stripe in my day job, so I plan to write about implementing card payments and convenience store payments at some point.
This article covers: a product list screen and detail screen using data registered in the DB, a (mock) purchase flow and purchase history display, and a shopping cart implementation. Authentication, error handling, and testing will be covered in separate articles.
Starting a Flask App with Docker
I’ll use Docker for this.
My usual approach is to start with a Dockerfile and docker-compose.yml, build the prototype inside the container, and keep notes on the commands used along the way.
FROM python:3.12.2-slim-bookworm
WORKDIR /app
RUN apt update -y && pip install --upgrade pip
version: '3.8'
services:
app:
build: .
tty: true
Create these two files, then run docker compose build and docker compose up -d to start the container.
Then enter the container and work from there.
First, let’s create a Flask app:
$ docker exec -it flask_web-app-1 /bin/bash
root@f7c40238f45c:/app# pip install Flask
root@f7c40238f45c:/app# touch main.py
root@f7c40238f45c:/app# apt install vim
Create main.py following the QuickStart, and install vim while we’re at it.
# main.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
Then start the Flask app:
root@f7c40238f45c:/app# flask --app main run
* Serving Flask app 'main'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
It’s running on port 5000, so exposing that port makes it accessible from the host.
I want to manage dependencies with requirements.txt, so let’s update the Dockerfile.
(These days, poetry looks appealing too.)
I prefer debian-based images, using slim variants when available. For production you’d want to run as a non-root user, but let’s skip that for now. This article uses whatever image is available even if it has vulnerabilities — use a different image or multi-stage build if you’re concerned.
FROM python:3.12.2-slim-bookworm
WORKDIR /app
COPY . /app
RUN apt update -y \
&& pip install --upgrade pip \
&& pip install -r requirements.txt
Flask>=3.0,<4.0
version: '3.8'
services:
app:
build: .
volumes:
- .:/app
ports:
- 5001:5000
command: bash -c "flask --app main run --host=0.0.0.0"
environment:
- FLASK_APP=main
- FLASK_DEBUG=on
- TZ=Asia/Tokyo
Create main.py on the host side as well and include it in the directory.
The host-side port is set to 5001.
Rebuild the container.
Note: be sure to set FLASK_APP in environment — omitting it causes an error later when using flask shell.
Setting FLASK_APP makes that module the app entry point, so you no longer need to pass --app on startup.
FLASK_DEBUG=on enables debug mode, which enables hot reload.
$ docker compose build
$ docker up -d
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d7590bc86543 flask_web-app "bash -c 'flask --ap…" 6 seconds ago Up 5 seconds 0.0.0.0:5001->5000/tcp flask_web-app-1
If you see Hello, World! at localhost:5001, you’re good to go.
Building a Standard CRUD API
Let’s build an API for data operations. First, we need to configure the database and build the data models.
Flask includes an interactive flask shell — we’ll use that to verify things as we go.
Ideally you’d do test-first development, but since testing isn’t the main topic here, it comes later.
The database is PostgreSQL. We’ll use Flask-SQLAlchemy for data models and Flask-Migrate for migrations.
Add Flask-SQLAlchemy and Flask-Migrate to requirements.txt and rebuild the container.
Also include psycopg2-binary, the PostgreSQL adapter (the binary version without compilation is fine for development and testing, but psycopg2 is recommended for production).
You can also just run pip install -r requirements.txt directly.
Flask-Migrate>=4.0,<5.0
Flask-SQLAlchemy>=3.1,<4.0
psycopg2-binary>=2.9,<3.0
Connecting to the DB
Before creating data models, add a DB container.
Set the password and user in environment, and expose port 5432 for DB inspection with a client like DBeaver.
Set volumes to specify a directory for data sync.
Here, we create a db/data directory inside the directory containing main.py.
version: '3.8'
services:
app:
build: .
volumes:
- .:/app
ports:
- 5001:5000
command: bash -c "flask run --host=0.0.0.0"
environment:
- FLASK_APP=main
- FLASK_DEBUG=on
- TZ=Asia/Tokyo
postgres:
image: postgres:16.2-bookworm
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
- POSTGRES_DB=postgres
- TZ=Asia/Tokyo
ports:
- 5432:5432
volumes:
- ./db/data:/var/lib/postgresql/data
Also configure the SQLAlchemy connection in main.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://postgres:postgres@postgres/postgres'
db = SQLAlchemy()
db.init_app(app)
migrate = Migrate()
migrate.init_app(app, db)
# continued below...
PostgreSQL now starts with docker compose up -d:
$ docker compose up -d
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e09f5794e54b postgres:16.2-bookworm "docker-entrypoint.s…" 40 seconds ago Up 39 seconds 0.0.0.0:5432->5432/tcp flask_web-postgres-1
a26ae3f560f2 flask_web-app "bash -c 'flask run …" 40 seconds ago Up 39 seconds 0.0.0.0:5001->5000/tcp flask_web-app-1
Connecting with DBeaver should show an empty database.
Creating Data Models
We’ll write the models in main.py for now and split them into files later.
First, create Product and User by inheriting from the previously defined db.Model.
Product has a name, price, created timestamp, and updated timestamp.
# omitted
from datetime import datetime, timezone
from sqlalchemy.orm import Mapped, mapped_column
# omitted
class Product(db.Model):
__tablename__ = 'products'
id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
name: Mapped[str] = mapped_column(db.String(20), nullable=False)
price: Mapped[int] = mapped_column(db.Integer, nullable=False)
created: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
updated: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
def __repr__(self) -> str:
return f'Product(id={self.id!r}, name={self.name!r}, price={self.price!r}, created={self.created!r}, updated={self.updated!r})'
class User(db.Model):
__tablename__ = 'users'
id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
name: Mapped[str] = mapped_column(db.String(20), nullable=False)
created: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
updated: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
def __repr__(self) -> str:
return f'User(id={self.id!r}, name={self.name!r}, created={self.created!r}, updated={self.updated!r})'
DB Migration
With the models in main.py, create the tables in the DB.
The DB should already be running when the Flask app starts, so just run:
# Enter the Docker container first
$ flask db migrate -m 'create products and users'
$ flask db upgrade
Inspecting the DB with DBeaver should show the products and users tables.
Verifying in the Shell
With the tables created, use flask shell to try creating and retrieving data via SQLAlchemy’s ORM.
First, create a Product:
$ flask shell
Python 3.12.2 (main, Mar 12 2024, 08:11:26) [GCC 12.2.0] on linux
App: main
Instance: /app/instance
>>> product = Product(name='Snack', price=100)
>>> db.session.add(product)
>>> db.session.commit()
Retrieve the Product:
>> product = db.session.execute(db.select(Product).filter_by(name='Snack')).scalar_one()
>> product
Product(id=1, name='Snack', price=100, created=datetime.datetime(2024, 3, 24, 18, 39, 26, 238131), updated=datetime.datetime(2024, 3, 24, 18, 39, 26, 238193))
>> products = db.session.query(Product).all()
>> products
[Product(id=1, name='Snack', price=100, created=datetime.datetime(2024, 3, 24, 18, 39, 26, 238131), updated=datetime.datetime(2024, 3, 24, 18, 39, 26, 238193))]
Looks good.
Building the EC Site Screens
Now let’s build the screens using DB data. The four screens are: product list, product detail, purchase history, and purchase.
First, create a base template. Here’s templates/base.html:
<!-- base.html -->
<!DOCTYPE html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" />
</head>
<body>
<header>{% block header %}{% endblock %}</header>
<main>{% block content %}{% endblock %}</main>
</body>
Individual page content fills the block header and block content sections.
Product List
Create templates/products.html extending base.html.
Since we’re creating a detail screen next, include a link to it too:
<!-- products.html -->
{% extends 'base.html' %} {% block header %}
<h1>{% block title %}Products{% endblock %}</h1>
{% endblock %} {% block content %}
<section>
{% for product in products %}
<dt>
<a href="/products/{{ product.id }}">{{ product.name }}</a>
</dt>
<dd>{{ product.price }}</dd>
{% endfor %}
</section>
{% endblock %}
Add the following below the hello_world() method in main.py.
This retrieves all records from the products table and passes them to the template as the products variable:
@app.route("/products")
def products():
products = db.session.query(Product).all()
return render_template('products.html', products=products)
The template iterates over products and displays each product’s name and price.
Product Detail
We could create a separate detail screen, but let’s combine them.
The template below behaves as a detail screen when product is passed, and as a list screen when products is passed:
<!-- products.html -->
{% block content %}
<section>
{% if product %}
<dt>{{ product.name }}</dt>
<dd>{{ product.price }}</dd>
{% elif products %} {% for product in products %}
<dt>
<a href="/products/{{ product.id }}">{{ product.name }}</a>
</dt>
<dd>{{ product.price }}</dd>
{% endfor %} {% endif %}
</section>
{% endblock %}
Add a product method to main.py:
@app.route("/products/<product_id>")
def product(product_id):
product = db.session.execute(db.select(Product).filter_by(id=product_id)).scalar_one()
return render_template('products.html', product=product)
Adding Products to the Cart
Cart data is stored in the session. In production you’d persist cart contents to the DB or use other approaches. With authentication, you could use sessions before login and the DB after.
Add an add_cart() method as follows.
You can import session from Flask and store a cart list with the specified product_id values:
from flask import Flask, render_template, session, request, redirect, url_for
# omitted
@app.post('/add_cart')
def add_cart():
cart_items = []
if 'cart' in session:
cart_items = session['cart']
if request.form['product_id'] not in cart_items:
cart_items.append(request.form['product_id'])
session['cart'] = cart_items
return redirect(url_for('cart'))
See the Flask sessions documentation for reference.
Add an “Add to Cart” button on the product detail screen.
The code below checks an in_cart variable (Boolean) — if false, the “Add to Cart” button is displayed.
The in_cart variable is returned from the product() method:
<!-- products.html -->
<!-- omitted -->
<dt>{{ product.name }}</dt>
<dd>{{ product.price }}</dd>
{% if not in_cart %}
<form action="/add_cart" method="post">
<input type="hidden" name="product_id" value="{{ product.id }}" />
<input type="submit" value="Add to Cart" />
</form>
{% endif %}
<!-- omitted -->
@app.route("/products/<product_id>")
def product(product_id):
product = db.session.execute(db.select(Product).filter_by(id=product_id)).scalar_one()
in_cart = False
# Returns True if product_id is in session cart
if 'cart' in session and product_id in session['cart']:
in_cart = True
return render_template('products.html', product=product, in_cart=in_cart)
Next, the cart item list screen:
<!-- cart.html -->
{% block content %}
<section>
{% for product in products %}
<p>{{ product.name }}</p>
<form action="/remove_cart" method="post">
<input type="hidden" name="product_id" value="{{ product.id }}" />
<input type="submit" value="Remove from Cart" />
</form>
{% endfor %}
<a href="/products">Browse Products</a>
</section>
{% endblock %}
On the API side, add remove_cart() and cart():
@app.post('/remove_cart')
def remove_cart():
# Only remove product_id from cart if session has cart
if 'cart' in session:
cart_items = session['cart']
cart_items.remove(request.form['product_id'])
session['cart'] = cart_items
return redirect(url_for('cart'))
@app.route("/cart")
def cart():
# Initialize empty products list
products = []
if 'cart' in session:
# Extract Products from DB based on product_ids in cart
cart_items = session['cart']
app.logger.info(cart_items)
products = db.session.query(Product).filter(Product.id.in_(cart_items)).all()
# Make products available in the template
return render_template('cart.html', products=products)
This completes adding to cart, removing from cart, and listing cart items.
Purchase
Before implementing purchase, create a table to record the fact that a user purchased a product.
We already have a users table, so now create purchase_transactions as a junction table between products and users:
class PurchaseTransaction(db.Model):
__tablename__ = 'purchase_transactions'
id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
product_id: Mapped[int] = mapped_column(db.ForeignKey('products.id'))
user_id: Mapped[int] = mapped_column(db.ForeignKey('users.id'))
product: Mapped['Product'] = db.relationship(back_populates='purchase_transactions')
user: Mapped['User'] = db.relationship(back_populates='purchase_transactions')
created: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
updated: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
def __repr__(self) -> str:
return f'PurchaseTransaction(id={self.id!r}, product_id={self.product_id!r}, user_id={self.user_id!r} created={self.created!r}, updated={self.updated!r})'
Also update Product and User to reference PurchaseTransaction:
class Product(db.Model):
__tablename__ = 'products'
id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
name: Mapped[str] = mapped_column(db.String(20), nullable=False)
price: Mapped[int] = mapped_column(db.Integer, nullable=False)
purchase_transactions: Mapped[List['PurchaseTransaction']] = db.relationship(back_populates='product', cascade='all, delete-orphan') # accessible as product.purchase_transactions
created: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
updated: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
def __repr__(self) -> str:
return f'Product(id={self.id!r}, name={self.name!r}, price={self.price!r}, created={self.created!r}, updated={self.updated!r})'
class User(db.Model):
__tablename__ = 'users'
id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
name: Mapped[str] = mapped_column(db.String(20), nullable=False)
purchase_transactions: Mapped[List['PurchaseTransaction']] = db.relationship(back_populates='user', cascade='all, delete-orphan') # accessible as user.purchase_transactions
created: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
updated: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
def __repr__(self) -> str:
return f'User(id={self.id!r}, name={self.name!r}, created={self.created!r}, updated={self.updated!r})'
Let’s run a quick creation test in flask shell:
root@d4d07ffc9c48:/app# flask shell
Python 3.12.2 (main, Mar 12 2024, 08:11:26) [GCC 12.2.0] on linux
App: main
Instance: /app/instance
>>>
>>> user = db.session.execute(db.select(User).filter_by(id=1)).scalar_one()
>>> product = db.session.execute(db.select(Product).filter_by(id=1)).scalar_one()
>>> purchase_transaction = PurchaseTransaction(user=user, product=product)
>>> db.session.add(purchase_transaction)
>>> db.session.commit()
>>>
>>> user.purchase_transactions
[PurchaseTransaction(id=1, product_id=1, user_id=1 created=datetime.datetime(2024, 1, 1, 12, 0, 0, 0), updated=datetime.datetime(2024, 1, 1, 12, 0, 0, 0))]
>>>
>>> product.purchase_transactions
[PurchaseTransaction(id=1, product_id=1, user_id=1 created=datetime.datetime(2024, 1, 1, 12, 0, 0, 0), updated=datetime.datetime(2024, 1, 1, 12, 0, 0, 0))]
The relations are working.
The purchase API is the purchase() method below. The purchaser user is hardcoded to id=1 for now — in a real app you’d retrieve the user ID from the session.
After purchase, success.html is displayed.
In a real EC site, you’d call a payment API like Stripe before or after creating the PurchaseTransaction.
@app.post("/purchase/<product_id>")
def purchase(product_id):
user = db.session.execute(db.select(User).filter_by(id=2)).scalar_one()
product = db.session.execute(db.select(Product).filter_by(id=product_id)).scalar_one()
if user and product:
purchase_transaction = PurchaseTransaction(user=user, product=product)
db.session.add(purchase_transaction)
db.session.commit()
return render_template('success.html', product=product)
{% block content %}
<section>
<p>Successfully purchased {{ product.name }}!</p>
<a href="/products">Browse Products</a>
<a href="/cart">View Cart</a>
</section>
{% endblock %}
In a typical EC site, purchases are made from the cart, so place the purchase button on the cart screen. Purchases are made per item — bulk purchase is not implemented here.
The cart screen looks like this:
<!-- cart.html -->
{% block content %}
<section>
{% for product in products %}
<p>{{ product.name }}</p>
<form action="/purchase/{{ product.id }}" method="post">
<input type="hidden" name="product_id" value="{{ product.id }}" />
<input type="submit" value="Purchase" />
</form>
<form action="/remove_cart" method="post">
<input type="hidden" name="product_id" value="{{ product.id }}" />
<input type="submit" value="Remove from Cart" />
</form>
{% endfor %}
<a href="/products">Browse Products</a>
</section>
{% endblock %}
Purchasing from the cart and showing the success screen is now complete.
Inspecting the DB with DBeaver should show a new purchase_transactions record.
Purchase History
Finally, let’s display a list of purchased products.
Add a transactions() method and render transactions.html:
@app.route("/transactions")
def transactions():
purchase_transactions = db.session.query(PurchaseTransaction).all()
return render_template('transactions.html', transactions=purchase_transactions)
<!-- transactions.html -->
{% block content %}
<section>
{% for transaction in transactions %}
<dt>You purchased {{ transaction.product.name }}.</dt>
<dd>You paid {{ transaction.product.price }}.</dd>
{% endfor %}
<a href="/products">Browse Products</a>
<a href="/cart">View Cart</a>
</section>
{% endblock %}
Add a link to the purchase history screen in cart.html:
<!-- cart.html -->
<!-- omitted -->
<a href="/transactions">View Purchase History</a>
<!-- omitted -->
Clicking the “Purchase” button added earlier should now display the purchased product in transactions.html.
Appendix
For forms, there’s a library called Flask WTF that handles HTML form building and validation nicely.
It’s an adaptation of WTForms for Flask — the original docs are also useful.
Using it also lets you handle CSRF protection, which I’ll cover in the next Flask article. I’ve also heard that using the Origin header for CSRF protection is gaining popularity, so I’ll touch on that too.
Source code: here