I ran into an issue where I assigned request.user to a variable called prior_user, then essentially authenticated the user, then checked to see if request.user != prior_user. I expected them not to be the same and that prior_user should contain `AnonymousUser. To my surprise, they were the same.
Sample code:
prior_user = request.user # request object, obtained froma view
authenticate_user(request) # some function that authenticates
print prior_user.username != request.user.username # returns False i.e.they are the same!
I then discovered prior_user actually contains an instance of django.utils.functional.SimpleLazyObject so I assume it is some sort of lazy lookup type thing i.e. prior_user’s value isn’t looked up until actually used. Looking at the source code, I cannot confirm this.
Anyone with django experience can tell me what is going on and why it is needed?
This leaves me a little shaken, because the usual assignment statement doesn’t work the way I expect and what else within Django acts like this? Nor did I see this described in the docs.
So anyone with super human knowledge of django can provide some clarity?
The
authmiddleware adds auserattribute torequestthat is an instance ofSimpleLazyObject.SimpleLazyObject, itself is a subclass ofLazyObject.LazyObjectis, as described by the actual code:SimpleLazyObjectmerely sets that class (the_wrappedattribute onLazyObject) via a passed in method, in this case,get_user. Here’s the code for that method:That in itself is really just a wrapper around
auth.get_user, that enables a sort of caching mechanism. So here’s what actually is eventually run:So, all that’s really going on here is that
request.useris ambiguous until it’s actually used for something. This is important, because it allows it to adapt depending on the current authentication status. If you access a property on it before you authenticate, it returns an instanceAnonymousUser, but if you authenticate and then access it, it returns an instance ofUser.