code: def retryable_transaction(attempts=3, exceptions=(OperationalError,)):
      
      assert len(exceptions) > 0
      assert attempts > 0
  
      def wrapper(f):
          @functools.wraps(f)
          def wrapped(*args, **kwargs):
              for i in xrange(attempts):
                  try:
                      return f(*args, **kwargs)
                  except exceptions, e:
                      if i == (attempts - 1):
                          raise
                      logging.warning(
                          'Retryable error in transaction on attempt %d. %s: %s',
                          i + 1, e.__class__.__name__, e)
                      db.session.rollback()
  
          return wrapped
  
      return wrapper
docs: Decorator retries a function when expected exceptions are raised.