0

I am building a GAE web app that receives a JSON file through a HTTP POST and persist the data into the application's datastore.

I was able to parse the incoming JSON file to my NDB Model class with the following code:

jsonContent = json.loads(self.request.body)
myTransaction = Transaction()
myTransaction.populate(**jsonContent)
myTransaction.put()

This is the content of the JSON file:

{"name": "Fabio", "message": "Hello World!"}

The challenge I am facing is that this JSON should also include an ID value to be stored in the "Key Name" column of a datastore entity. I tried adding "key_name":"1" or "id":"1" to the JSON file, but the populate() method does not understand them as valid attributes. Instead, when first instantiating the myTransaction object, I had to traditionally set the constructor to Transaction(id="1"). However, the content for attribute ID is stored in the JSON file along with the rest of the data. It doesn't make any sense to actually programatically open the JSON to retrieve each ID and set the constructor before calling populate(). In fact, this does not even work because populate() would still try to parse the attribute ID within the JSON file.

Does anyone know how to parse a JSON file that includes the "Key Name" attribute to a NDB Model class and persist it do the application's datastore?

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
Fabio Moggi
  • 405
  • 1
  • 4
  • 12

1 Answers1

0

The key does not exist until you put() it. If you need the key as part of the JSON object, you could append it:

the_key = myTransaction.put()
the_id = the_key.id()
jsonContent['the_id'] = the_id

ndb and db are different. ndb does not use key_name:

db: MyModel(key_name='my_key')
ndb: MyModel(id='my_key')

You could insert your custom id after populating, like this:

myTransaction["id"] = the_id
myTransaction.put()
GAEfan
  • 11,244
  • 2
  • 17
  • 33
  • Thanks for answering. I am actually referring to the Key Name, not the Key that is generated after inserting data. – Fabio Moggi Nov 22 '14 at 18:38
  • The problem with the approach you described is that the ID(Key Name) is embedded into the JSON that is processed by the populate() method. I would like to avoid manually decoding the JSON file to figure out the value for ID and then assigning it to the object after populate() is executed. Not sure if this is something possible, though. – Fabio Moggi Nov 22 '14 at 18:56
  • The answer for this topic may be related to what I am talking about, but I don't have the proper knowledge to correlates the solution with my needs: http://stackoverflow.com/questions/13311363/appengine-making-ndb-models-json-serializable "It's probably worth noting that the to_dict does not include the key in the model. So you may wish to do something like json.dumps([dict(p.to_dict(), **dict(id=p.key.id())) for p in ... – Brian M. Hun" – Fabio Moggi Nov 22 '14 at 19:02