开发者

App Engine: create object inside a transaction

开发者 https://www.devze.com 2023-01-10 14:52 出处:网络
I\'m writing a site on GAE-Java + Objectify which lets users create their own pages, with unique URL. I haven\'t been able to figure out a clear way to ensure that when two users try to claim the same

I'm writing a site on GAE-Java + Objectify which lets users create their own pages, with unique URL. I haven't been able to figure out a clear way to ensure that when two users try to claim the same url at the same time, only one user gets it.

This is what I'm trying to avoid:

  • User 1 does a开发者_高级运维 check - its available
  • User 2 does a check - its available
  • Meanwhile, User 1 creates page and stores it.
  • User 2 creates a page and overwrites User 1.

Any ideas on how to solve this on GAE?


Why not just run your code in a transaction? I don't see where the issue is. Do you have a sample of something you've tried and had problems with?


Found a clearer explanation in the python docs:

Attempts to get the entity of the model's kind with the given key name. If it exists, get_or_insert() simply returns it. If it doesn't exist, a new entity with the given kind, name, and parameters in kwds is created, stored, and returned. The get and subsequent (possible) put are wrapped in a transaction to ensure atomicity. Ths means that get_or_insert() will never overwrite an existing entity, and will insert a new entity if and only if no entity with the given kind and name exists. In other words, get_or_insert() is equivalent to this Python code:

def txn():
  entity = MyModel.get_by_key_name(key_name, parent=kwds.get('parent'))
  if entity is None:
    entity = MyModel(key_name=key_name, **kwds)
    entity.put()
  return entity

return db.run_in_transaction(txn)
0

精彩评论

暂无评论...
验证码 换一张
取 消