GAE: How to rollback a transaction?

情到浓时终转凉″ 提交于 2019-12-12 03:28:54

问题


I just read this great summary of GAE best practices: https://cloud.google.com/datastore/docs/best-practices

One of them is:

If a transaction fails, ensure you try to rollback the transaction. The rollback minimizes retry latency for a different request contending for the same resource(s) in a transaction. Note that a rollback itself may fail, so the rollback should be a best-effort attempt only.

I thought that transaction rollback was something that GAE did for you, but the above quote says that you should do it yourself.

The documentation here also says you should do a rollback but does not say how.

So, how do I rollback a transaction in GAE Python?


回答1:


The best practices document is for using the Cloud Datastore directly through its API or client libraries.

This is only necessary in the flexible Appengine environment. Even in this case, the Cloud Datastore client library provides a context manager to automatically handle rollbacks - this example code is from the docs

def transfer_funds(client, from_key, to_key, amount):
    with client.transaction():
        from_account = client.get(from_key)
        to_account = client.get(to_key)

        from_account['balance'] -= amount
        to_account['balance'] += amount

        client.put_multi([from_account, to_account])

The docs state:

By default, the transaction is rolled back if the transaction block exits with an error

Be aware that the client library is still in Beta, so the behaviour could change in future.

In the standard Appengine environment, the ndb library provides automatic transaction rollback:

The NDB Client Libary can group multiple operations in a single transaction. The transaction cannot succeed unless every operation in the transaction succeeds; if any of the operations fail, the transaction is automatically rolled back.



来源:https://stackoverflow.com/questions/41700447/gae-how-to-rollback-a-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!