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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A context processor makes derived values available to every template without repeating logic in each view.
- 2Layering request-scoped state on top of a shared cache avoids both redundant lookups and stale database queries.
- 3Deriving flags like is_authenticated and is_admin once keeps template conditionals simple and consistent.
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
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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
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/injecting-the-current-user-in-flask-templates-explained-python-a179/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.