Performance: Authentication middleware
This affects the server response time and the time to first byte, impacting how quickly the page starts loading for authenticated users.
Jump into concepts and practice - no test required
class EfficientAuthMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user = request.session.get('user') if not user: user = fast_token_check(request) if not user: return redirect_to_login() request.session['user'] = user request.user = user response = self.get_response(request) return response
class SlowAuthMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user = authenticate_user_expensive_check(request) if not user: return redirect_to_login() request.user = user response = self.get_response(request) return response
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Expensive auth check every request | N/A (server-side) | N/A | N/A | [X] Bad |
| Cached auth with session | N/A (server-side) | N/A | N/A | [OK] Good |
AuthenticationMiddleware?request.user so views can access user info easily.request.user on every request -> Option CAuthenticationMiddleware in Django's settings.py?print(request.user.is_authenticated) output if the user is logged in?request.user is a User object or AnonymousUser.request.user.is_authenticated returns True.request.user.is_authenticated is True if logged in [OK]AuthenticationMiddleware to your Django project but request.user is always AnonymousUser. What is the most likely cause?AnonymousUser.AuthenticationMiddleware to achieve this?request.userrequest.user.is_authenticated to allow or block access before views run.request.user.is_authenticated in your custom middleware before view runs -> Option B