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
import threading from functools import wraps
A thread-safe debounce decorator in Python
decorators
debounce
threading
Advanced
6 steps
python
from urllib.parse import urlparse, parse_qs from dataclasses import dataclass, field ALLOWED_SCHEMES = {"http", "https"}
Validating URLs into a safe endpoint in Python
input validation
url parsing
dataclasses
Intermediate
7 steps
python
import pytest from fastapi.testclient import TestClient from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker
Testing FastAPI routes with dependency overrides
testing
fixtures
dependency-injection
Intermediate
7 steps
python
import hashlib import os from datetime import timedelta
Serving cacheable static assets in Flask
http-caching
etag
conditional-requests
Intermediate
8 steps
python
import re from collections import Counter from pathlib import Path
Ranking the top words in a PDF
text-processing
regex
counting
Intermediate
6 steps
python
import django_filters from django import forms from django.utils import timezone
Building a date-range FilterSet in Django
filtering
querysets
form-widgets
Intermediate
6 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.