Search code examples
pythongoogle-app-enginesessiongoogle-cloud-datastorewebapp2

Why can't I add an attribute to a datastore object (dynamically) and store it in session?


I am not able to retrieve attributes in session that have been added dynamically to a datastore object. Here's a (simplified) example... To save time on suggestions, I do not want to actually hard code the attribute to the datastore object.

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

Any idea as to why this happens?


Solution

  • When you redirect to a new script, I assume it's with another HTTP request?

    On a new request you're going to be using a new instance of the session object. Between your requests, your session would have been serialized and saved to memcache or the datastore. On your new request, you would have deserialized your session.

    You might want to check how the serialization went and why your user object wasn't serialized as you expected. Most likely the User class has its own serialization code based off the Kind attributes, and temp_var may be ignored by the serialization since it's not part of the class.

    You might also put temp_var directly in the session, in which case it should serialize properly.