Regarding AuthenticationMiddleware
, why did Django 1.3 handle the user
property at class level,
and why was it changed to an instance property in 1.4?
This is from 1.3
class LazyUser(object):
def __get__(self, request, obj_type=None):
if not hasattr(request, '_cached_user'):
from django.contrib.auth import get_user
request._cached_user = get_user(request)
return request._cached_user
class AuthenticationMiddleware(object):
def process_request(self, request):
request.__class__.user = LazyUser()
return None
And this from 1.4
def get_user(request):
if not hasattr(request, '_cached_user'):
request._cached_user = auth.get_user(request)
return request._cached_user
class AuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
request.user = SimpleLazyObject(lambda: get_user(request))
# SimpleLazyObject inherits from LazyObject
In 1.3, I understood that process_request
assigned LazyUser()
to the class level user
attribute, which to me basically means two things:
- The
HttpRequest
class (request.__class__
) stored itsuser
attribute between two requests, so futurerequest
objects had access to it. - Whenever a view function tried to access
request.user
, theLazyUser
object's__get__
method was triggered and returned a user object, either from the request's cache or from auth storage.
Am I correct about it?
Also, I have noticed in 1.4 these two major changes:
SimpleLazyObject
is assigned torequest
, not to its class (so, it is an instance property).LazyObject
andSimpleLazyObject
don't define (customize) their own__get__
method.
This way, when is get_user
triggered?
How does AuthenticationMiddleware
now store request.user between two requests, and override the statelessness of Http?