#NEWLINE# def add_db_object( session , table , exception_when_existing = True , * args , **kwargs ) : #NEWLINE# #INDENT# 'Create db object.\n\n    If not exception_when_existing and the db object exists,\n    Instead of raising exception, updating the existing db object.\n    ' #NEWLINE# if ( not session ) : #NEWLINE# #INDENT# raise exception . DatabaseException ( 'session param is None' ) #NEWLINE# #UNINDENT# with session . begin ( subtransactions = True ) : #NEWLINE# #INDENT# logging . debug ( 'session %s add object %s atributes %s to table %s' , id ( session ) , args , kwargs , table . __name__ ) #NEWLINE# argspec = inspect . getargspec ( table . __init__ ) #NEWLINE# arg_names = argspec . args [ 1 : ] #NEWLINE# arg_defaults = argspec . defaults #NEWLINE# if ( not arg_defaults ) : #NEWLINE# #INDENT# arg_defaults = [ ] #NEWLINE# #UNINDENT# if ( not ( ( len ( arg_names ) - len ( arg_defaults ) ) <= len ( args ) <= len ( arg_names ) ) ) : #NEWLINE# #INDENT# raise exception . InvalidParameter ( ( 'arg names %s does not match arg values %s' % ( arg_names , args ) ) ) #NEWLINE# #UNINDENT# db_keys = dict ( zip ( arg_names , args ) ) #NEWLINE# if db_keys : #NEWLINE# #INDENT# db_object = session . query ( table ) . filter_by ( ** db_keys ) . first ( ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# db_object = None #NEWLINE# #UNINDENT# new_object = False #NEWLINE# if db_object : #NEWLINE# #INDENT# logging . debug ( 'got db object %s: %s' , db_keys , db_keys ) #NEWLINE# if exception_when_existing : #NEWLINE# #INDENT# raise exception . DuplicatedRecord ( ( '%s exists in table %s' % ( db_keys , table . __name__ ) ) ) #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# db_object = table ( ** db_keys ) #NEWLINE# new_object = True #NEWLINE# #UNINDENT# for ( key , value ) in kwargs . items ( ) : #NEWLINE# #INDENT# setattr ( db_object , key , value ) #NEWLINE# #UNINDENT# if new_object : #NEWLINE# #INDENT# session . add ( db_object ) #NEWLINE# #UNINDENT# session . flush ( ) #NEWLINE# db_object . initialize ( ) #NEWLINE# db_object . validate ( ) #NEWLINE# logging . debug ( 'session %s db object %s added' , id ( session ) , db_object ) #NEWLINE# return db_object