On Google App Engine, I would like to create a unique key for a data table. As suggested by this, I am trying to do the following:
Suppose I have a model called Message, and the field values are obtained from a web page as follows:
message = db.Message()
message.name = self.request.get('name')
message.email = self.request.get('email')
...
message.put()
message.messageId = message.key().id()
message.put()
I have two questions:
-
Is this the correct way of creating a unique id (messageId)? I mean: put the entity first, get it’s id and assign to messageId, and finally put again? It looks strange.
-
How to prevent the concurrency problem? I know that I can use ‘transaction’ as follows:
@db.transactional def storeEntity(): message.name = self.request.get('name') message.email = self.request.get('email') ... message.put() message.messageId = message.key().id() message.put()
But what if this transaction fails? How do I do it until it is successful? Thanks in advance.
When you do not provide a key, the datastore will return a key for you, so you do not have to put the entity twice. And put will return the key.
So you can :