[Twisted-Python] Problems using Twisted adbapi

Thomas Weholt thomas.weholt at gmail.com
Wed Sep 29 17:47:37 EDT 2004


Hi,

My code below is an attempt to write a general database-abstraction
layer for Twisted. I got one allready supporting SQLite and MySQL (
MSSQL and PostgreSQL in the works ) but it blocks and doesn't use
deffereds etc so I thought I'd try to write one that fits better with
the Twisted framework. It will mainly be used in web-applications. The
basic example is ( and don't laugh, this is my first attempt at using
deferreds etc. ) :

from twisted.enterprise import adbapi

class TestConn:

    def __init__(self, dbname):
        self.dbname = dbname
        self.dbpool = adbapi.ConnectionPool("sqlite", db=dbname)

    def returnOk(self, o):
        return True

    def returnFailure(self, o):
        return False

    def returnResult(self, result):
        return result

    def _returnResult(self, deferred, count = None):
        if count:
            return self.dbpool.fetchmany(count)
        else:
            return self.dbpool.fetchall()

    def execSql(self, sql, params = {}):
        def run(sql, params):
            return self.dbpool.runQuery(sql, params)
        d = run(sql, params)
        d.addCallback(self._returnResult)
        d.addErrback(self.returnFailure)
        d.addCallback(self.returnResult)

    def fetch(self, sql, params = {}):
        def run(sql, params):
            return self.dbpool.runQuery(sql, params)
        d = run(sql, params)
        d.addCallback(self.returnResult)
        d.addErrback(self.returnFailure)

s = TestConn(r'c:\temp\db1.db')
print s.execSql('create table table1 (a int, b int)')
print s.execSql('insert into table1 (a,b) values (1,1)')
print s.execSql('insert into table1 (a,b) values (1,2)')
print s.execSql('insert into table1 (a,b) values (2,2)')
print s.fetch('select * from table1')
print s.fetch('select a from table1')

And the result is :

None
None
None
None
None
None

Why ??? What I want is a general purpose "connection"-class which can
execute queries and fetch data from a database, without having to
create special methods returning deferreds, adding callbacks etc. to
get the result of the query.

-- 
Mvh/Best regards,
Thomas Weholt
http://www.weholt.org




More information about the Twisted-Python mailing list