Session variable fetched into a local var changes when operating on the local one
i noticed a strange behaviour when 开发者_JS百科interacting with session variables in Django. In one of my app i created a middleware.py file containing a function that copy a session variable that stores an object into a local one and then i change an attribute of the object from the local var. It happens that the changes i make to the local variable are applied also to the session variable. It seems that the local var is only a reference to the session. Is this behaviour correct? Here's the code:
class CloudMiddleware(object):
user = request.session['user']
user.email = 'myemail'
When i do
user = request.session['user']
email = user.email
The value of email is equal to 'myemail'. I always thought i had to save my object back in the session if i want to store it. Could someone explain me how it really works?
This is nothing to do with sessions, but a simple consequence of how Python mutable objects work. When you do user = request.session['user']
you are getting a reference to the object, exactly as you would with any other mutable object stored in a standard dictionary. So yes, when you change one of its attributes, that change is referenced in any other reference you have to it.
Note that for sessions, this change will only be persisted in the lifetime of the current request. That's because Django can't know the session object has changed, so won't save it unless you specifically tell it to - see the documentation for details.
user
is a mutable object, so it's passed by reference. Anything is correct.
精彩评论