python
49 lines · 8 steps
Nesting Flask Blueprints for an admin panel
An admin blueprint guards every route and hosts a nested users blueprint that lists, toggles, and deletes accounts.
Explained by
highlit
1from flask import Blueprint, render_template, request, redirect, url_for, flash, abort
2from .models import User, AuditLog
3from .extensions import db
4from .decorators import admin_required
5
6admin = Blueprint("admin", __name__, url_prefix="/admin", template_folder="templates/admin")
7
8users = Blueprint("users", __name__, url_prefix="/users")
9
10
11@admin.before_request
12@admin_required
13def restrict_to_admins():
14 pass
15
16
17@admin.route("/")
18def dashboard():
19 return render_template("admin/dashboard.html", user_count=User.query.count())
20
21
22@users.route("/")
23def index():
24 page = request.args.get("page", 1, type=int)
25 pagination = User.query.order_by(User.created_at.desc()).paginate(page=page, per_page=25)
26 return render_template("admin/users/index.html", pagination=pagination)
27
28
29@users.route("/<int:user_id>/toggle-active", methods=["POST"])
30def toggle_active(user_id):
31 user = User.query.get_or_404(user_id)
32 user.is_active = not user.is_active
33 db.session.add(AuditLog(actor_id=request.current_user.id, action="toggle_active", target=user.id))
34 db.session.commit()
35 flash(f"{user.email} is now {'active' if user.is_active else 'disabled'}.", "success")
36 return redirect(url_for("admin.users.index"))
37
38
39@users.route("/<int:user_id>", methods=["DELETE"])
40def destroy(user_id):
41 user = User.query.get_or_404(user_id)
42 if user.id == request.current_user.id:
43 abort(422, description="You cannot delete your own account.")
44 db.session.delete(user)
45 db.session.commit()
46 return "", 204
47
48
49admin.register_blueprint(users)
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A before_request guard on a blueprint enforces authorization for every route it owns in one place.
- 2Nesting one blueprint inside another composes URL prefixes and namespaces endpoints hierarchically.
- 3Recording an AuditLog alongside a state change ties destructive actions to the actor who performed them.
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/nesting-flask-blueprints-for-an-admin-panel-explained-python-3510/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.