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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Guarding a single view by HTTP method lets one route both render a form and process its submission.
- 2Redirecting after a failed or successful POST keeps flash messages clean and prevents duplicate submissions.
- 3Changing a sensitive field like email should re-verify the password and reset any confirmation state.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-change-email-route-in-flask-explained-python-57db/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.