[Twisted-Python] adbapi and multiple queries in single transaction.
Phil Christensen
phil at bubblehouse.org
Tue Jun 23 08:25:16 MDT 2009
On Jun 23, 2009, at 9:45 AM, Vishal Shetye wrote:
> I initially thought of putting all the queries per operation in a
> runInteraction. However this results in code-duplication as many
> queries are shared between different operations.
It seems like the easiest way to deal with this would be to make
'private' methods for all the standard queries; these methods/
functions would accept a transaction object like you said, but the
methods themselves would only be called from an interaction, which can
supply the transaction object.
Then in each public ObjectGateway method you can just define an inner
function to serve as the interaction, calling each private query
method in turn, using the transaction object provided to that
interaction.
Here's a stupidly trivial example:
class ObjectGateway(object):
def __init__(self, pool):
self.pool = pool
def _getUserName(self, trans, user_id):
result = trans.execute('SELECT username FROM user WHERE id =
%s', user_id);
return result[0][0]
def _sessionUpdateQuery(self, trans, sid, username):
trans.execute('UPDATE session SET username = %s WHERE sid =
%s', [username, sid]);
def handleLogin(self, sid, user_id):
def _loginInteraction(trans):
u = self._getUserName(trans, user_id)
self._sessionUpdateQuery(trans, sid, username)
return u
return self.pool.runInteraction(_loginInteraction)
Other than being careful not to mess around with the instance state
during those interactions (they are running in a thread, after all),
this should be pretty straightforward.
Hope this helps,
-phil
More information about the Twisted-Python
mailing list