This is the code:
def create_game(user_id):
game = classes.Games(user_id = user_id)
game.put()
def get_game(user_id):
game_query = classes.Games.gql('WHERE user_id = :1', user_id)
game = False
for item in game_query:
game = item
if not game:
create_game(user_id)
get_game(user_id)
else:
return game
def render_page(self):
message = 'this is a game page<br>'.decode('utf-8')
user = creditentials.get_user(self)
if not user:
self.redirect('/')
return
game = get_game(user.key().id())
message += 'current game ID: '.decode('utf-8') + str(game.key().id())
self.response.write(message)
I expect it to create just one instance of the game, instad it creates 10! Appearantly GQL query is perfromed asynchronously, and starting from the 3rd (?) instance of the get_game(user_id)
it just skips game_query = classes.Games.gql('WHERE user_id = :1', user_id)
line.
Am I right? How do I avoid this?
Queries aren't immediately consistent, so an entity that you've only just created won't be returned in a query performed right-away, you need to wait a bit.
In your case, you don't need to query for the entity - you just created it, so you know it exists, and can use it. Change your create_game function to return the new game, and then use that.
If you expect your user_id to be unique (and given your query, this seems to be the case) you could use it as the entity-id, then you can get-by-id instead of querying, which will strongly-consistent.
Check the "Data Consistency" section on this docs page for more detail on how queries work.