Skip to content

Instantly share code, notes, and snippets.

Created January 19, 2015 19:33
Show Gist options
  • Save anonymous/bd79b5515ce3904a3010 to your computer and use it in GitHub Desktop.
Save anonymous/bd79b5515ce3904a3010 to your computer and use it in GitHub Desktop.
def autocommit(fn):
def wrapper(*args, **kwargs):
self = args[0]
cmd = fn(*args, **kwargs)
if isinstance(self, Transaction):
self.commands.append(cmd)
return cmd
else:
return cmd.execute()
return wrapper
class Command(object):
def __init__(self, cmd, name):
self.cmd = cmd
self.name = name
def execute(self):
return (self.cmd, self.name)
class API(object):
def __init__(self, context):
self.context = context
@autocommit
def br_exists(self, name):
return Command('br_exists', name)
@autocommit
def db_list(self, name):
return Command('db_list', name)
class Transaction(API):
def __init__(self):
self.commands = []
self.results = []
def commit(self):
for cmd in self.commands:
cmd.result = cmd.execute()
self.results.append(cmd.result)
return self.results
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
return self.commit()
def __str__(self):
return "Transaction results: %s" % self.results
API.transaction = Transaction
class BaseOVS(object):
def __init__(self):
self.ovsdb = API(self)
def bridge_exists(self, name):
# Look ma, no execute!
return self.ovsdb.br_exists(name)
def db_list(self, name):
# Look ma, no execute!
return self.ovsdb.db_list(name)
def multi_cmd(self, name1, name2):
with self.ovsdb.transaction() as txn:
# instead of:
# a = txn.add(self.ovsdb.br_exists('mybridge'))
# b = txn.add(self.ovsdb.db_list('mydblist'))
a = txn.br_exists(name1)
b = txn.db_list(name2)
print "a returned:", a.result
print "b returned:", b.result
return txn.results
if __name__ == '__main__':
ovs = BaseOVS()
a = ovs.bridge_exists('mybridge')
b = ovs.db_list("mydblist")
c = ovs.multi_cmd("mybridge", "mydblist")
print [a, b]
print c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment