python 32 lines · 6 steps

Injecting the current user in Flask templates

A context processor resolves the logged-in user once per request with request-scoped and cross-request caching, then exposes it to every template.

Explained by highlit
1from flask import g, session
2 
3from .extensions import cache
4from .models import User
5 
6 
7@app.context_processor
8def inject_current_user():
9 def load_user():
10 if "current_user" in g:
11 return g.current_user
12 
13 user_id = session.get("user_id")
14 if user_id is None:
15 g.current_user = None
16 return None
17 
18 user = cache.get(f"user:{user_id}")
19 if user is None:
20 user = User.query.filter_by(id=user_id, is_active=True).first()
21 if user is not None:
22 cache.set(f"user:{user_id}", user, timeout=300)
23 
24 g.current_user = user
25 return user
26 
27 user = load_user()
28 return {
29 "current_user": user,
30 "is_authenticated": user is not None,
31 "is_admin": bool(user and user.role == "admin"),
32 }
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1A context processor makes derived values available to every template without repeating logic in each view.
  2. 2Layering request-scoped state on top of a shared cache avoids both redundant lookups and stale database queries.
  3. 3Deriving flags like is_authenticated and is_admin once keeps template conditionals simple and consistent.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Injecting the current user in Flask templates — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code