0

I have a form that submits POST data to a handler, creates and puts a datastore entry called Item. Then it redirects the page and a GET request is sent where the datastore entry is queried as such:

    query = Item.query()
    userLessons = query.filter(Item.author == thisUser)
    itemQuery = userLessons.filter(Item.name == itemName).fetch(1)
    desiredItem = itemQuery[0]

The rendered page results in an error UnboundLocalError: local variable 'desiredItem' referenced before assignment. If I simply refresh the page and send another GET request the datastore entry is magically present. How is this possible? I tried adding the same query to the bottom of the POST before the redirect after putting the Item, and I get the same error. Is there a better way to query?

1 Answer 1

1

Datastore operations are asynchronous. It make take up to a couple of seconds for an entity to become available in a query after it is inserted in the Datastore. You have two possible solutions:

  1. Add this entity to the Memcache before saving it to the Datastore. On the subsequent request, check the Memcache first, and only after that query the Datastore. In most cases you will won't have to query the Datastore at all. This method will save you some reading costs.

  2. Since you need a single entity, do not use a query at all. Use an id of your entity to retrieve it:

Retrieving Entities from Keys

The best solution is to combine these methods.

4
  • Thanks for the tip on asynchronous operations. Thinking of trying a while loop in the GET request that queries until the datastore query has a length greater than 0. Only one entity is added, and it's an operation that will be done infrequently.
    – TomNash
    Jul 17, 2014 at 1:11
  • You don't want to do a loop for this. In particular, your Datastore query is eventually consistent: cloud.google.com/developers/articles/…. This means that it could take much longer than a request for your query to return up to date information. If you need your query to return up to date results, you need to make it strongly consistent by using an ancestor and specifying a parent when you create your model. Jul 22, 2014 at 23:11
  • @Patrick - get() operations are always strongly consistent. There is no need for an ancestor query when you need one entity and you know its key. Jul 22, 2014 at 23:55
  • @AndreiVolgin I totally agree, using a get is the right solution. I was responding to user3220769's comment about doing a loop and continuously querying for a length > 0. If they were to do this, they would need a strongly consistent query (and then no loop). Jul 22, 2014 at 23:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.