在Google App Engine中,如何避免使用相同的属性创建重复的实体? [英] In Google App Engine, how do I avoid creating duplicate entities with the same attribute?

查看:113
本文介绍了在Google App Engine中,如何避免使用相同的属性创建重复的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图添加一个事务来保持创建具有相同属性的两个实体。在我的应用程序中,每当看到新的Google用户登录时,我都会创建一个新玩家。当几个毫秒内由新的Google用户创建多个json电话时,我当前的实现偶尔会创建重复播放器。当我添加像这里评论的那样的交易时,我会收到各种错误。确保我从不创建具有相同user_id的两个玩家实体的最简单方法是什么?

I am trying to add a transaction to keep from creating two entities with the same attribute. In my application, I am creating a new Player each time I see a new Google user logged in. My current implementation occasionally creates duplicate players when multiple json calls are made by a new Google user within a few milliseconds. When I add the transaction like the one commented out here, I get various errors. What is the easiest way to ensure that I never create two player entities with the same user_id?

  def get_player_from_user(self, user_id):
    player = Player.all().filter('user_id =', user_id).get()    
    if not player:
        #This can result in duplicate players with the same user_id being created. 
        player = self.create_new_player(user_id)
        #This is what I'm trying to do. 
        #player = db.run_in_transaction(self.create_new_player, user_id=user_id)
    return player

  def create_new_player(self,user_id):
        #Check one more time for an existing user_id match.  
        player = Player.all().filter('user_id =', user_id).get()
        if player:
           return player

        player = Player()
        player.user_id = user.user_id()
        player.put()
        return player


推荐答案

使用用户名(或其他标识符)作为键名,并使用 get_or_insert 以事务方式创建新实体或返回现有实体。 Sahid的代码将不起作用,因为没有交易,竞争条件仍然是可能的。

Use the username (or other identifier) as the key name, and use get_or_insert to transactionally create a new entity or return the existing one. Sahid's code won't work, because without a transaction, a race condition is still possible.

这篇关于在Google App Engine中,如何避免使用相同的属性创建重复的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆