Is there a way to return the result of a dictionary from an adbapi query in MySQL?
[name: 'Bob', phone_number: '9123 4567']
By default, the tuple is returned.
['Bob', '9123 4567']
For simple Python and 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 a better way. My solution: just override the * _runInteraction * method of the 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
source
share