Tastypie 文档指出,捆绑包使 Tastypie 更加线程安全,但没有解释如何以及在什么条件下。我已经查看了代码,但是没有足够的经验来解决它。
我正在制作一个游戏原型,它有一个圆形对象(对于每一轮比赛)和每一轮的多个状态(对于该轮每个玩家的信息)。每个玩家都会通过对回合单词短语的回答来更新自己的状态。我需要一种机制来懒惰地创建下一轮游戏,如果它还不存在的话。我目前在玩家更新他们的状态时触发该轮创建。
如果多个玩家同时更新他们的状态(见StateResource.obj_update()
),那么他们创建下一轮的尝试会发生冲突吗?我认为如果一个obj_update
调用检查下一轮是否存在并尝试在另一个obj_update
完成创建下一轮之前创建下一轮,则可能会发生这种情况。我会用某种类型的互斥锁来解决这个问题,但我不确定这是否有必要。我想知道是否有一种美味的方式来解决这个问题。
我的代码如下:
#models.py
class Round(models.Model):
game_uid = models.CharField(max_length=75)
word = models.CharField(max_length=75)
players = models.ManyToManyField(User)
next_round = models.OneToOneField('self',null=True,blank=True)
class PlayerRoundState(models.Model):
player = models.ForeignKey(User)
round = models.ForeignKey(Round)
answer = models.CharField(max_length=75)
#api.py
class RoundResource(ModelResource):
players = fields.ManyToManyField(UserResource, attribute='players',full=False)
states = fields.ManyToManyField('wordgame.api.StateResource',
attribute='playerroundstate_set',
full=True)
. . .
def obj_create(self, bundle, request=None, **kwargs):
bundle = super(RoundResource, self).obj_create(bundle, request,**kwargs)
bundle.obj.word = choice(words) #Gets a random word from a list
bundle.obj.round_number = 1
bundle.obj.game_uid = bundle.obj.calc_guid() #Creates a unique ID for the game
bundle.obj.save()
return bundle
class StateResource(ModelResource):
player = fields.ForeignKey(UserResource, 'player',full=False)
round = fields.ForeignKey(RoundResource, 'round')
. . .
def obj_update(self, bundle, request=None, skip_errors=False, **kwargs):
bundle = super(StateResource, self).obj_update(bundle, request,
skip_errors, **kwargs)
if bundle.obj.round.next_round is None:
new_round = Round()
new_round.word = choice(words)
new_round.round_number = bundle.obj.round.round_number + 1
new_round.game_uid = bundle.obj.round.game_uid
new_round.save()
for p in bundle.obj.round.players.all():
new_round.players.add(p)
new_round.save()
bundle.obj.round.next_round = new_round
bundle.obj.round.save()
return bundle