0

I need to be able to write data to datastore of google-app-engine for some known entity. But I don't want write assignment code for each parameter of the entity. I meen, I don't want do like this

val_1 = self.request.get('prop_1')
val_2 = self.request.get('prop_2')
...
val_N = self.request.get('prop_N')
item.prop_1 = val_1
item.prop_2 = val_2
...
item.prop_N = val_N
item.put()

instead, I want to do something like this

args = self.request.arguments()
  for prop_name in args:
    item.set(prop_name, self.request.get(prop_name))
item.put()

dose anybody know how to do this trick?

this question is similar to mine but it seems that this guy wants only to read data. I need to write!

Community
  • 1
  • 1
  • 1
    Related: http://stackoverflow.com/questions/746942/adding-a-user-supplied-property-at-runtime-to-an-instance-of-expando-class-in – Shay Erlichmen Nov 25 '11 at 18:38

2 Answers2

0

You need to use the Expando class.

The Expando class is a superclass for data model definitions whose properties are determined dynamically. An Expando model can have a combination of fixed properties similar to Model and dynamic properties assigned to an entity at run-time

Shay Erlichmen
  • 31,691
  • 7
  • 68
  • 87
  • thank you, but it is not for my case. In my case, prop_name is string that I take from *request* object and I don't see a method to use it in Expando too. – Maxim Welikobratov Nov 25 '11 at 17:54
  • @MaximWelikobratov item.setattr(name, value) should do the trick, but the item needs to be an expando. – Shay Erlichmen Nov 25 '11 at 18:09
  • It seems that Expando dose not have setattr. I can't find description of this method and it say my fast tests *"AttributeError: 'super' object has no attribute 'setattr'"* – Maxim Welikobratov Nov 25 '11 at 18:27
  • look at: http://stackoverflow.com/questions/746942/adding-a-user-supplied-property-at-runtime-to-an-instance-of-expando-class-in – Shay Erlichmen Nov 25 '11 at 18:38
0

You can do this using exec, but I would not recommend it at all. Please consider the security implications involved with this. eg. the possibility that a user posts a new key for your object thus potentially hijacking the object.

If you must do it, however, the exec method would definitely help you, as described here (the link also contains more reasons why this is probably not a good idea).

Proceed at your own risk.

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • This is a spectacularly bad idea, especially since Python has built-in mechanisms for setting properties and attributes at runtime. – Nick Johnson Nov 28 '11 at 00:54