Skip to content

Instantly share code, notes, and snippets.



Last active Jun 26, 2020
What would you like to do?
Transactionnal decorator for Python & GCP Datastore
from import datastore
from .transactionnal import transactionnal
client = datastore.Client('<project-id>', '<namespace>')
key = <get a key somehow>
# > @transactionnal(client)
# > def _():
# is equivalent to
# > with client.transaction():
# but it cannot fail
def _():
player = client.get(key)
player['total_points'] += 10
from tenacity import retry, retry_if_exception_type, wait_random, stop_after_attempt
from google.api_core import exceptions
# Simple decorator to be able to reproduce the behaviour of the `with`
# keyword for transactions
def transactionnal(client, *args, **kwargs):
if callable(client):
raise TypeError('transactionnal() missing 1 required positional argument: \'client\'')
wait=wait_random(.1, .3),
def _(f):
with client.transaction():
f(*args, **kwargs)
return _

This comment has been minimized.

Copy link
Owner Author

@Nurrl Nurrl commented Jun 26, 2020


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment