Package Products :: Package ZenUtils :: Module transaction_contextmanagers
[hide private]
[frames] | no frames]

Source Code for Module Products.ZenUtils.transaction_contextmanagers

 1  ############################################################################## 
 2  #  
 3  # Copyright (C) Zenoss, Inc. 2010, all rights reserved. 
 4  #  
 5  # This content is made available according to terms specified in 
 6  # License.zenoss under the directory where your Zenoss product is installed. 
 7  #  
 8  ############################################################################## 
 9   
10   
11  # context managers for transaction and state commit/rollback 
12  from contextlib import contextmanager 
13   
14  import transaction 
15 16 # define exception type to catch cases where current transaction is explicitly 17 # committed or aborted with in the body of the with statement (only necessary on 18 # abort) 19 -class InvalidTransactionError(Exception): pass
20
21 @contextmanager 22 -def zodb_transaction():
23 try: 24 txn = transaction.get() 25 yield txn 26 except: 27 if txn is not transaction.get(): 28 raise InvalidTransactionError( 29 "could not abort transaction, was already aborted/committed within 'with' body") 30 try: 31 txn.abort() 32 # catch any internal exceptions that happen during abort 33 except Exception: 34 pass 35 raise 36 else: 37 try: 38 if txn is transaction.get(): 39 txn.commit() 40 # catch any internal exceptions that happen during commit 41 except Exception: 42 pass
43
44 @contextmanager 45 -def nested_transaction(xaDataManager=None):
46 try: 47 txn = transaction.get() 48 sp = txn.savepoint() 49 if xaDataManager is not None: 50 txn.join(xaDataManager) 51 yield 52 except: 53 try: 54 sp.rollback() 55 if xaDataManager is not None: 56 xaDataManager.abort(txn) 57 except: 58 pass 59 raise 60 else: 61 pass
62