python 35 lines · 8 steps

A change-email route in Flask

A Flask view that validates input, verifies the password, and updates a user's email with a confirmation reset.

Explained by highlit
1from flask import Blueprint, render_template, request, redirect, url_for, flash
2from werkzeug.security import check_password_hash
3 
4from .models import User, db
5 
6bp = Blueprint("account", __name__, url_prefix="/account")
7 
8 
9@bp.route("/change-email", methods=["GET", "POST"])
10def change_email():
11 if request.method == "GET":
12 return render_template("account/change_email.html")
13 
14 user = User.query.get_or_404(request.form["user_id"])
15 new_email = request.form.get("email", "").strip().lower()
16 password = request.form.get("password", "")
17 
18 if not new_email or "@" not in new_email:
19 flash("Please enter a valid email address.", "error")
20 return redirect(url_for("account.change_email"))
21 
22 if not check_password_hash(user.password_hash, password):
23 flash("That password is incorrect.", "error")
24 return redirect(url_for("account.change_email"))
25 
26 if User.query.filter_by(email=new_email).first():
27 flash("That email is already in use by another account.", "error")
28 return redirect(url_for("account.change_email"))
29 
30 user.email = new_email
31 user.email_confirmed = False
32 db.session.commit()
33 
34 flash("Your email was updated. Check your inbox to confirm it.", "success")
35 return redirect(url_for("account.settings"))
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Guarding a single view by HTTP method lets one route both render a form and process its submission.
  2. 2Redirecting after a failed or successful POST keeps flash messages clean and prevents duplicate submissions.
  3. 3Changing a sensitive field like email should re-verify the password and reset any confirmation state.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A change-email route in Flask — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code