Over the weekend I was writing some code in Google AppEngine and had a need to loop through all of the incoming request parameters so automatically update the contents of a model when there were request parameters which had the same name as the model attributes.
When I wrote the very first version of the AE chapters for the class – I had this bit about dumping parameters in one chapter. In the rewrite to send the book to O’Reilly, I felt that this detail was too much so I cut it out about a month ago. I also cleaned up old copies of the chapter on my hard drive and on the appenginelearn.com site.
So on Saturday, I am sitting here peeved that I had this all figured out once and had even written it up once – exactly what I wanted – and then lost it.
I figured that I had researched this once before – so I could figure it out again. I remember that there was no real documentation and I had to write stuff like dir() to hunt through methods. It was painful but I figured I could do it in an hour.
So I typed the following into Google:
appengine looping through request variables
I looked at the text of the second hit and it looked promising. Then I noticed the word “Michigan” in the text and then I noticed that it was *my chapter*. The lost chapter. So I clicked on the link (the PDF) and scrolled down and had my answer in about 45 seconds!
I had forgotten to remove the copy on my Michigan personal AFS space – which I had used while teaching the class – Google had found it, indexed it and knew *somehow* that it was what I needed.
Sweet!
Here is the code I used to loop throught the attributes from a request and update model values automatically:
# Loop through the request keys and see if they can be put
# into the model
def modelload(self, org, req, prefix = None):
self.debug("ORM LOAD "+str(org.__class__))
for key in req.params.keys():
value = self.web.request.get(key)
thetype = self.modeltype(org, key)
if ( thetype == "none" and prefix != None ) :
if ( not key.startswith(prefix) ) : continue
key = key[len(prefix):]
thetype = self.modeltype(org, key)
if ( thetype == "none" ) : continue
self.debug(key+" ("+thetype+") = "+value)
setattr(org,key,value)
def modeltype(self, obj, key):
try:
attr = str(type(getattr(obj.__class__, key)))
except :
return "none"
if attr.find("ext.db.StringProperty") > 0 : return "string"
if attr.find("ext.db.ReferenceProperty") > 0 : return "reference"
if attr.find("ext.db.DateTimeProperty") > 0: return "datetime"
if attr.find("ext.db.IntegerProperty") > 0: return "int"
return "none"
Here is the entire bit of code for folks who might be interested.
http://code.google.com/p/cloudcollab/source/browse/trunk/contrib/drchuck/wiscrowd/imsglobal/lti.py