Rollback Datastore PUT Transaction in GAE Python Web
<p>There is one method inside that method I'm inserting three different models record into database. But if some exception or error happens I need to rollback this insertion transaction from db.
Following is show case of method.</p>

<pre><code>def post():
    try:
        model1 = Model1()
        model1.key1 = 'key1'
        model1.key2 = 'key2'
        model1.put()

        #some logic1 code block goes here
        .
        .
        model2 = Model2()
        model2.key2 = 'key2'
        model2.key2 = 'key2'
        model2.put()

        #some logic2 code block goes here
        .
        .
        model3 = Model3()
        model3.key3 = 'key3'
        model3.key3 = 'key3'
        model3.put()

        #some logic3 block goes here
        .
        .
    except Exception:
        #all the database insertion transaction which happened should be rollback here.
</code></pre>

<p><strong>Here Model1, Model2 and Model3 are google.appengine.ext.ndb.Model extending model classes.</strong>
Now suppose exception occurred in <code>logic1 code block</code> then <code>model1</code> should be rollback because it was inserted before executing this <code>logic1 code block</code>. Similarly if exception occurred in <code>logic2 code block</code> then both above <code>model1 &amp; model2</code> should be rollback and so on. My problem is very common. I did lot of search but not able to find any solution. I'm totaly new in Python and GAE. Please help.</p>

<p>As <a href="http://stackoverflow.com/users/104349/daniel-roseman">@Daniel Roseman</a> linked for you, the answer is on the <a href="https://cloud.google.com/appengine/docs/python/ndb/transactions" rel="nofollow">NDB Transaction page</a>. Just search for the word "rollback" and you'll see it.</p>

<p>For your code, this means:</p>

<pre><code>@ndb.transactional(xg=True)
def post():
    try:
        model1 = Model1()
        model1.key1 = 'key1'
        model1.key2 = 'key2'
        model1.put()

        ...

        #some logic3 block goes here
        .
        .
    except Exception:
        #all the database insertion transaction which happened should be rollback here.
        raise ndb.Rollback
</code></pre>

<p>Note that on the decorator I've specified <code>xg-True</code> since from your code snippet it looked like it was most likely a cross-entity group transaction. If this is not the case and all entities have the same root ancestor, you can omit this.</p>

<p>Also note that ndb.Rollback is purely a convenience exception - any exception raised in a transaction decorated function will cause a rollback.</p>

python google-app-engine google-cloud-datastore rollback