Is there any way to return dictionary result from adbapi query to MySQL?
[name: 'Bob', phone_number: '9123 4567']
Default returns tuple.
['Bob', '9123 4567']
For simple Python & MySQL we can use MySQLdb.cursors.DictCursor. But how to use it with twisted adbapi
UPD: I solved it but I think there should be better way. My solution: just override *_runInteraction* method of adbapi.ConnectionPool class.
class MyAdbapiConnectionPool(adbapi.ConnectionPool):
def _runInteraction(self, interaction, *args, **kw):
conn = self.connectionFactory(self)
trans = self.transactionFactory(self, conn)
try:
result = interaction(trans, *args, **kw)
if(result and isinstance(result[0], (list, tuple))):
colnames = [c[0] for c in trans._cursor.description]
result = [dict(zip(colnames, item)) for item in result]
trans.close()
conn.commit()
return result
except:
excType, excValue, excTraceback = sys.exc_info()
try:
conn.rollback()
except:
log.err(None, 'Rollback failed')
raise excType, excValue, excTraceback
You can direct MySQLdb to use
DictCursorby passing it as the value for thecursorclassargument to theconnectfunction.ConnectionPoolallows you to pass arbitrary arguments through to the connect method:When you run a query, you’ll get a
dictback instead of a tuple, egrunQuery("SELECT 1")produces a result of({'1': 1L},)