[英]Session variable fetched into a local var changes when operating on the local one
i noticed a strange behaviour when interacting with session variables in Django. 我在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. 在我的一个应用程序中,我创建了一个middleware.py文件,其中包含一个函数,该函数将存储对象的会话变量复制到本地变量中,然后从本地变量中更改对象的属性。 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. 似乎本地var只是对会话的引用。 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'. 电子邮件的价值等于'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? 有人可以解释一下它是如何运作的吗?
user
is a mutable object, so it's passed by reference. user
是一个可变对象,因此它通过引用传递。 Anything is correct. 一切都是正确的。
This is nothing to do with sessions, but a simple consequence of how Python mutable objects work. 这与会话无关,而是Python可变对象如何工作的简单结果。 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. 当您执行user = request.session['user']
您将获得对该对象的引用,就像存储在标准字典中的任何其他可变对象一样。 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. 那是因为Django不知道会话对象已经改变了,所以除非你明确告诉它,否则不会保存它 - 请参阅文档了解详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.