我想知道 db.run_in_transaction() 是否充当数据存储操作的锁 并有助于在同一实体上并发访问。
在下面的代码中是否保证并发访问不会导致竞争并且不会创建新实体而不是进行覆盖
db.run_in_transaction() 是正确的/最好的方法吗
在下面的代码中,我试图用下面的代码创建新的唯一实体
def txn(charmer=None):
new = None
key = my_magic() + random_part()
sk = Snake.get_by_name(key)
if not sk:
new = Snake(key_name=key, charmer= charmer)
new.put()
return new
db.run_in_transaction(txn, charmer)
最佳答案
这是一种安全的方法。如果同一个名称生成两次,则只会创建一个实体。
听起来您已经看过 transactions文档。还有一个更detailed description .
查看 Model.get_or_insert
上的文档(特别是等效代码) , 它准确回答了您提出的问题:
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.
关于python - 并发访问应用引擎中的数据存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4321876/