I'm confused with HttpRequest object in Django. I know that the AuthenticationMiddleware will add a user to request which is an instance of HttpRequest. And the code is here, but what I want to show is as follow:
request.user = SimpleLazyObject(lambda: get_user(request))
I have read the code of HttpRequest object and can not find a user attribute and its code don't have a __setattr__ method. So I'm curious about why the code do not raise an AtrributeError when access to a no existing attribute.
Thanks for giving help.
HttpRequest is a class which inherits from object. In Python attributes can be set on objects at any time.
HttpRequest describes a HTTP request, which in its normal state does not include any data about the user. That is why the AuthenticationMiddleware adds user to the request.
__setitem__ is the method for setting indexed items on an object.
__setattr__ is the method for setting an attribute on an object, and is one of the methods implemented in object.
UPDATE
As @sayse said that is getting.
>>> class Test(object):
pass
>>> test = Test()
>>> test.user #Try to access an unset attribute
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
test.user #Try to access an unset attribute
AttributeError: 'Test' object has no attribute 'user'
>>> test.user = 'user' #Set user attribute
>>> test.user #Try to access user
'user'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With