[Twisted-Python] Twisted.web and adbapi example?

Mario Ruggier mario at ruggier.org
Thu May 15 10:27:34 EDT 2003


An example that uses threads (and not adpapi) is in January's mail  
achive, at:
http://twistedmatrix.com/pipermail/twisted-python/2003-January/ 
002694.html

Here's some old code that uses adpapi (save as a .rpy):

###

from twisted.web import resource
from twisted.web.server import NOT_DONE_YET

dbname = 'test'
dbuser = 'dbuser'
dbpass = 'dbpass'

from twisted.enterprise import row
class FooRow(row.RowObject):
   rowColumns = [
           ('foo_id', 'int'),
           ('name', 'varchar'),
           ('weight', 'int'),
                ]
   rowKeyColumns = [('foo_id', 'int4')]
   rowTableName = 'foo'
   #rowFactoryMethod = ['testFactoryMethod']

def databaseResult_adbapi(result, httpRequest):
     if result:
         for foo in result:
             httpRequest.write('foo: '+str(foo.__dict__)+'<br/>')
     else:
         httpRequest.write('stop:')
     httpRequest.finish()

def errBack_adbapi(err, httpRequest):
     httpRequest.write('error: '+str(err) )
     httpRequest.finish()

class MyResource_adbapi(resource.Resource):
     def render(self, request):
         from twisted.enterprise import adbapi, reflector
         from twisted.enterprise.sqlreflector import SQLReflector
         dbpool =  
adbapi.ConnectionPool('pyPgSQL.PgSQL',database=dbname,user=dbuser,passwo 
rd=dbpass)
         r = SQLReflector(dbpool,[FooRow])
         d = r.loadObjectsFrom('foo',whereClause=[('foo_id',  
reflector.LESSTHAN, 5)])
         d.addCallback(databaseResult_adbapi, request)
         d.addErrback(errBack_adbapi, request)
         return NOT_DONE_YET

resource = MyResource_adbapi()

###

> I've been pouring through the docs and examples, but can't find an
> example of a .rpy that generates a page containing the results of a
> database query.  How would such a thing be properly architected?
> Clearly the adbapi would be involved, but then how do I get the query
> results into the string returned by my resource?  Or would I use a
> deferred instead?
>
> Would someone please share a little code snippet (or point me at
> one)illustrating how that would best be accomplished?
>
> Thanks.





More information about the Twisted-Python mailing list