Building E-Commerce Features with Flask ②
CREATED: 2024 / 04 / 06 Sat
UPDATED: 2024 / 04 / 06 Sat
Continuing from Part 1
This continues from Building an EC Site with Flask ①, covering forms and CSRF.
When building Flask applications that require POST operations, you typically set up a form in HTML.
The Flask WTF form library (building forms on the Python side and rendering them in HTML) isn’t strictly required, but it comes with validation features, so there’s generally no reason not to use it.
Forms are built using a library called Flask WTF.
Building Forms with Flask WTF
First, add Flask-WTF to requirements.txt.
Also add email-validator since we want email validation:
Flask-WTF>=1.2,<2.0
email-validator>=2.1,<3.0
Importing FlaskForm and related classes into main.py from the previous article, a signup form looks like this.
Since we’re not covering authentication here, treat this as a simple user data creation form:
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import InputRequired, Length, Email
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
# omitted
csrf = CSRFProtect()
csrf.init_app(app) # Enable CSRF protection
class SignUpForm(FlaskForm):
name = StringField('name', validators=[InputRequired(), Length(min=1, max=20)])
email = StringField('email', validators=[InputRequired(), Email()])
The users table from the previous article didn’t have an email column, so update the User class and run migrations again.
The email column is unique and not nullable. name is also now unique:
class User(db.Model):
__tablename__ = 'users'
id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
name: Mapped[str] = mapped_column(db.String(20), unique=True, nullable=False)
email: Mapped[str] = mapped_column(db.String(100), unique=True, nullable=False)
purchase_transactions: Mapped[List['PurchaseTransaction']] = db.relationship(back_populates='user', cascade='all, delete-orphan')
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})'
Enter the container and run flask db migrate and flask db upgrade:
root@d4d07ffc9c48:/app# flask db migrate -m 'change user'
INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
INFO [alembic.ddl.postgresql] Detected sequence named 'purchase_transactions_id_seq' as owned by integer column 'purchase_transactions(id)', assuming SERIAL and omitting
INFO [alembic.autogenerate.compare] Detected added column 'users.email'
INFO [alembic.autogenerate.compare] Detected added unique constraint None on '('email',)'
INFO [alembic.autogenerate.compare] Detected added unique constraint None on '('name',)'
Generating /app/migrations/versions/1070adbc40d0_change_user.py ... done
root@13582844164c:/app# flask db upgrade
With the table updated, let’s integrate the form into the HTML.
Create sign_up.html.
It imports render_field from _formhelpers.html, which defines the form field prototype.
Just place render_field inside the form:
<!-- sign_up.html -->
{% extends 'base.html' %} {% from "_formhelpers.html" import render_field %} {% block header %}
<h1>{% block title %}SignUp{% endblock %}</h1>
{% endblock %} {% block content %}
<section>
<form method="post">
{{ form.csrf_token }}
<dl>
{{ render_field(form.name, placeholder="name") }} {{ render_field(form.email,
placeholder="email") }}
</dl>
<input type="submit" value="Sign Up" />
</form>
</section>
{% endblock %}
And _formhelpers.html:
<!-- _formhelpers.html -->
{% macro render_field(field) %}
<dt>{{ field.label }}</dt>
<dd>
{{ field(**kwargs)|safe }} {% if field.errors %}
<ul class="errors">
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}
Don’t forget to add the sign_up() API — it accepts both GET and POST, so list both in methods.
Pass request.form to the SignUpForm defined above. If validation passes, create a User and redirect to the product list page (/products).
If validation fails, the user is returned to sign_up.html:
@app.route("/sign_up", methods=('GET', 'POST'))
def sign_up():
form = SignUpForm(request.form)
if form.validate_on_submit():
name = form.name.data
email = form.email.data
user = User(name=name, email=email)
db.session.add(user)
db.session.commit()
return redirect(url_for('products'))
return render_template('sign_up.html', form=form)
That’s all it takes — validation and CSRF protection are now in place.
Try entering an invalid email format and you’ll see Invalid email address..
For CSRF: a token generated from the secret_key set in main.py is embedded in the form. It’s verified on POST, and if verification passes, sign_up() executes normally.
The CSRF token can be replaced by cookie settings or Origin header validation for same-origin requests, but since implementation isn’t particularly difficult, just do it properly. Security vulnerabilities can appear in unexpected forms, and issues that only a CSRF token can prevent may be discovered (however unlikely).
Cookie and Origin header validation will be covered in the upcoming authentication article. Authentication isn’t implemented yet, so CSRF isn’t currently possible — making it a bit awkward to explain in context here.
Appendix
That covers forms. Next up: authentication.