为什么我不能将属性添加到数据存储对象(动态)并将其存储在会话中?

时间:2013-04-23 15:29:24

标签: python google-app-engine session google-cloud-datastore webapp2

我无法检索会话中已动态添加到数据存储区对象的属性。这是一个(简化的)示例...为了节省建议的时间,我不想将属性硬编码到数据存储区对象。

Class User(ndb.Model):
   email = ndb.String...


// I use a handler to get the user object from the datastore 
// and store the object in session
user = function_to_get_user_by_key(key)

// Add an temporary attribute
user.temp_var = 'test'

// Store in session
self.session['user'] = user

// Get the user in the same script to test the attribute
user = self.session.get('user')

print user.temp_var // Works - I see the result


// Redirect to a new script (By the way, assume these scripts are in separate methods       within a handler class)

user = self.session.get('user')
print user.temp_var // Gives an attribute error - basically saying the class does not have this attribute

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

当您重定向到新脚本时,我认为它与另一个HTTP请求有关吗?

在新请求中,您将使用会话对象的新实例。在您的请求之间,您的会话将被序列化并保存到memcache或数据存储区。根据您的新请求,您可以对会话进行反序列化。

您可能想要检查序列化的方式以及用户对象未按预期序列化的原因。很可能User类有自己的基于Kind属性的序列化代码,并且序列化可能会忽略temp_var,因为它不属于类。

您也可以将temp_var直接放在会话中,在这种情况下,它应该正确序列化。