Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twisted MySQL adbapi return dictionary

Tags:

python

twisted

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
like image 554
imilbaev Avatar asked Dec 07 '11 07:12

imilbaev


1 Answers

You can direct MySQLdb to use DictCursor by passing it as the value for the cursorclass argument to the connect function. ConnectionPool allows you to pass arbitrary arguments through to the connect method:

import MySQLdb
pool = ConnectionPool("MySQLdb", ..., cursorclass=MySQLdb.cursors.DictCursor)
...

When you run a query, you'll get a dict back instead of a tuple, eg runQuery("SELECT 1") produces a result of ({'1': 1L},)

like image 135
Jean-Paul Calderone Avatar answered Oct 10 '22 21:10

Jean-Paul Calderone