[Twisted-Python] Problems using Twisted adbapi
exarkun at divmod.com
exarkun at divmod.com
Wed Sep 29 16:12:04 MDT 2004
On Wed, 29 Sep 2004 23:47:37 +0200, Thomas Weholt <thomas.weholt at gmail.com> wrote:
>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. ) :
Hey Thomas,
I think you're pretty close. See below for a couple minor code changes.
>
> 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)
return d
>
> 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)
return d
>
> 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')
>
With the two added returns, you should no longer see None in the output, although you will also not see your actual results. I think this is what you expected, though.
Jp
More information about the Twisted-Python
mailing list