Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpRequest instance add attribute dynamically in Django?

Tags:

python

django

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.

like image 405
chyoo CHENG Avatar asked May 10 '26 11:05

chyoo CHENG


1 Answers

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'
like image 64
James Fenwick Avatar answered May 12 '26 09:05

James Fenwick