[SQLObject] DTO : a simple implementation by proxy
SQLObject is a Python ORM.
Brought to you by:
ianbicking,
phd
From: G. <fra...@cl...> - 2003-07-08 08:43:50
|
Hi all, I've made this very little piece of code to implement DTO pattern. I know using __getattr__ is not so speed as using properties, but I'm not yet a great meta-programmer ;-) Usage : # loading SQLObject pers = Person(1) # creating DTO persDTO = SQLObjectProxy(pers) # no UPDATE request is done while setting attributes persDTO.firstname = 'Dark' persDTO.lastname = 'Vador' # UPDATE request is done here persDTO.save() Maybe I'll add a getDTO method on SQLObject, or pass an argument to constructor Here's my code snippet : ############################################################################## class SQLObjectProxy: """ SQLObjectProxy implements a simple proxy for SQLObject to save network traffic by explicit saving, because SQLObject does a request each time an attribute is set. By calling the save() method, all changes made to the object are saved in the database """ ########################################################################## def __init__( self, subject ): """ SQLObjectProxy contructor. @param subject: the SQLObject to wrap """ self.__subject = subject ########################################################################## def __getattr__( self, name ): """ Here is the heart of proxy : delegating attribute reading to the subject """ return getattr( self.__subject, name) ########################################################################## def save(self): """ The save method flushes all changes made to the object. """ kw = {} for colname in self._SO_columnDict.keys(): kw[colname] = getattr(self, colname) self.set(**kw) |