Building E-Commerce Features with Flask ④
CREATED: 2024 / 04 / 07 Sun
UPDATED: 2024 / 04 / 07 Sun
Error Handling
When you want to abort on an API error, import exceptions like BadRequest from werkzeug.exceptions and raise them at the appropriate point:
from werkzeug.exceptions import BadRequest, Unauthorized, NotFound, InternalServerError
@app.post("/sample")
def sample():
error = True
if error:
raise BadRequest
else:
return render_template('sample.html')
This does handle errors, but the error screen is predetermined and not customizable.
To customize it, register error handler methods with the app:
app = Flask(__name__)
# omitted
def handle_bad_request(e):
return render_template('error.html', e=e), 400
def handle_unauthorized(e):
return render_template('error.html', e=e), 401
def handle_not_found(e):
return render_template('error.html', e=e), 404
def handle_internal_server_error(e):
return render_template('error.html', e=e), 500
app.register_error_handler(400, handle_bad_request)
app.register_error_handler(401, handle_unauthorized)
app.register_error_handler(404, handle_not_found)
app.register_error_handler(500, handle_internal_server_error)
With this setup, raising BadRequest calls handle_bad_request, and raising InternalServerError calls handle_internal_server_error.
error.html is then rendered, with the error details passed as e and displayed on screen.
<!-- error.html -->
{% extends 'base.html' %} {% block header %}
<a href="/"><h1>{% block title %}Error{% endblock %}</h1></a>
{% endblock %} {% block content %}
<section>
<h1>Something went wrong.</h1>
<p>{{ e }}</p>
</section>
{% endblock %}
You can also wrap API methods in try except to catch other errors, if needed.
For example, sign_up() could look like this:
@app.route("/sign_up", methods=('GET', 'POST'))
def sign_up():
try:
if 'email' in session:
return redirect(url_for('products'))
form = SignUpForm(request.form)
if form.validate_on_submit():
name = form.name.data
email = form.email.data
password = form.password.data
salt = bcrypt.gensalt(rounds=12, prefix=b'2b')
hashpw = bcrypt.hashpw(password.encode('utf8'), salt)
user = User(name=name, email=email, password=hashpw.decode('utf8'))
db.session.add(user)
db.session.commit()
session['email'] = user.email
return redirect(url_for('products'))
return render_template('sign_up.html', form=form)
except Exception as e:
return render_template('sign_up.html', form=form, e=e)
In this case, update sign_up.html to display e:
<!-- sign_up.html -->
<form method="post">
{{ form.csrf_token }}
<dl>
{{ render_field(form.name, placeholder="name") }} {{ render_field(form.email,
placeholder="email") }} {{ render_field(form.password, placeholder="password") }}
</dl>
<input type="submit" value="Sign Up" />
<p>{{ e }}</p>
<!-- display e here -->
</form>
pytest
Before testing, it’s worth reorganizing the directory structure we’ve built so far.
Since tests need to call the API, we create a create_app() function that generates the Flask app, and call it from test files.
There are quite a few changes, so check the repository for full details. In summary: the code from main.py is moved into __init__.py, wrapped in create_app(), and main.py calls that to define app.
# __init__.py
def create_app():
app = Flask(__name__)
# omitted
if os.environ['FLASK_ENV'] == 'development':
app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://postgres:postgres@postgres/development'
else:
app.config["TESTING"] = True
app.config["WTF_CSRF_ENABLED"] = False
app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://postgres:postgres@postgres/test'
# omitted
from . import views
app.register_blueprint(views.bp)
return app
# main.py
from . import create_app
app = create_app()
Key changes: the DB is now switched by environment variable, and APIs are moved to a separate file (views.py). views.py references app via a Blueprint:
# views.py
bp = Blueprint("views", __name__)
@bp.route("/sign_up", methods=('GET', 'POST'))
# omitted
Forms and models are also extracted into their own files and imported into views.
Back in __init__.py, the database is split between development and test environments.
Databases are created from SQL files in docker-entrypoint-initdb.d when the PostgreSQL container starts.
The docker-compose.yml postgres service reads ./db/initdb.d via volumes, which contains the SQL file:
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
- ./db/initdb.d:/docker-entrypoint-initdb.d
The SQL file contains:
CREATE DATABASE development;
CREATE DATABASE test;
The contents of docker-entrypoint-initdb.d are executed on container startup, so these databases are created when PostgreSQL launches.
Next, separate development and test containers in docker-compose.yml, each with their own FLASK_ENV in environment.
These are referenced by the conditional in __init__.py above:
dev_app:
build: .
volumes:
- .:/app
ports:
- 5001:5000
command: bash -c "flask run --host=0.0.0.0"
environment:
- FLASK_APP=main
- FLASK_DEBUG=on
- FLASK_ENV=development
- TZ=Asia/Tokyo
test_app:
build: .
volumes:
- .:/app
command: bash -c "flask run --host=0.0.0.0"
environment:
- FLASK_APP=main
- FLASK_DEBUG=on
- FLASK_ENV=test
- TZ=Asia/Tokyo
Restart the containers and verify the development environment still works as before. Then enter the test container to proceed with testing.
Create a tests directory at the top level.
Inside it, create __init__.py and conftest.py.
__init__.py can be empty. conftest.py contains:
import pytest
from .. import create_app, db
@pytest.fixture()
def app():
app = create_app()
# set up
with app.app_context():
db.create_all()
yield app
# tear down
with app.app_context():
db.drop_all()
@pytest.fixture()
def client(app):
return app.test_client()
@pytest.fixture()
def runner(app):
return app.test_cli_runner()
This file handles test initialization. The set up comment section prepares test data, and the tear down section drops all data.
Actual tests go in files with a test_ prefix, in the same directory as conftest.py.
As a sample, tests for the signup feature look like this:
from flask import session
from .. import db
import bcrypt
from ..models import User
def test_sign_up_get(client):
with client:
response = client.get('/sign_up')
assert response.status_code == 200
def test_sign_up_post(client):
name = "test"
email = "[email protected]"
password = "hogehoge"
with client:
response = client.post('/sign_up', data={
"name": name,
"email": email,
"password": password
})
assert response.status_code == 302
assert session.get('email') == email
user = db.session.execute(db.select(User).filter_by(email=email)).scalar_one_or_none()
assert user.name == name
assert user.email == email
assert bcrypt.checkpw(password.encode('utf8'), user.password.encode('utf8'))
def test_sign_up_user_already_exists(app, client):
name = "test"
email = "[email protected]"
password = "hogehoge"
with app.app_context():
salt = bcrypt.gensalt(rounds=12, prefix=b'2b')
hashpw = bcrypt.hashpw(password.encode('utf8'), salt)
data = User(name=name, email=email, password=hashpw.decode('utf8'))
db.session.add(data)
db.session.commit()
with client:
response = client.post('/sign_up', data={
"name": name,
"email": email,
"password": password
})
assert response.status_code == 200
assert session.get('email') is None
The repository also includes sign-in and sign-out tests — check there if needed.
The boilerplate around create_app() hints at Flask’s complexity, but it’s something you get used to.
That’s it for testing.
Appendix
This series covered building a web application with Flask, specifically modeled after an EC site. The UI is bare-bones, but the core features are covered. There’s much more depth to explore, and this shouldn’t be taken as a complete guide to web application development — but hopefully it works as an introduction.
Flask may not be something I use much going forward, but I might write something with FastAPI at some point.