Transactions

sheraf.transactions.attempt(function, attempts=5, commit=<function <lambda>>, log_exceptions=True, args=None, kwargs=None, also_except=None, on_failure=<function <lambda>>)[source]

This method attemps to execute a function several times until no ConflictError is encountered.

Parameters:
  • function – The function to execute.

  • args – The positionnal arguments to pass to the function.

  • kwargs – The keyword arguments to pass to the function.

  • attempts – The number of attempts.

  • commit – An executable returning a boolean indicating wether to commit after executing function.

  • log_exceptions – A boolean indicating wether to log exceptions.

  • also_except – A tuple containing exception classes. If one of those exceptions is catched during the attempt, a new execution will be attempted.

  • on_failure – Callback called after each failed attempt except the last one. By default it waits a random time between 0 and attempts. The callback takes one argument nb_attempt.

Returns:

The return value of function.

Example:

>>> with sheraf.connection():
...     try:
...         sheraf.attempt(do_amazing_stuff, attempts=5, args=("DANGER",))
...     except ZODB.POSException.ConflictError:
...         print("Impossible to commit do_amazing_stuff after 5 attempts.")
...
>>> with sheraf.connection():
...     try:
...         sheraf.attempt(lambda: 1/0, also_except=(ZeroDivisionError,))
...     except ZeroDivisionError:
...         print("This has very few chances to be successful ¯\\_(ツ)_/¯")
This has very few chances to be successful ¯\_(ツ)_/¯
sheraf.transactions.commit(f=None)[source]

Wrapper shortcut for attempt().

>>> class Cowboy(sheraf.Model):
...     table = "cowboy"
...     dead = sheraf.BooleanAttribute(default=False)
...
>>> @sheraf.commit
... def fight(winner, loser):
...      loser.dead = True
...
>>> with sheraf.connection(commit=True):
...     winner = Cowboy.create()
...     loser = Cowboy.create()
...
>>> with sheraf.connection():
...     fight(winner, loser)
...
>>> with sheraf.connection():
...     Cowboy.read(loser.id).dead
True