3

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.

4
  • 1
    I don't understand what you're asking about, Python will allow you to add a property/field where needed?.. Commented Jun 2, 2016 at 8:12
  • if HttpRequest don't have an attribute like user, then you write request.user will raise AttributeError.@Sayse Commented Jun 2, 2016 at 8:19
  • But any time you do need to use it it will have the attribute since it is added in the auth middleware. Are you trying to use it in your own middleware before this middleware has been ran? Commented Jun 2, 2016 at 8:21
  • No, what I want to ask is why the code do not raise AttributeError. Commented Jun 2, 2016 at 8:24

1 Answer 1

6

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'
Sign up to request clarification or add additional context in comments.

4 Comments

"In Python attributes can be set on objects at any time." I'm doubt about this words.class Test(object):pass , t = Test(), then t.user will raise an AttributeError.
@chyooCHENG - That is getting, not setting. (Nicely written btw, James Fenwick)
I have understood it. Thanks all!
And I want to know why it can run, is that the object achieves the __setarr__ method ? @James Fenwick

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.