[Twisted-Python] deferreds, and .rpy resources

L. Daniel Burr ldanielburr at earthlink.net
Thu Jan 23 18:25:42 MST 2003


On Thu, 23 Jan 2003, Mario Ruggier wrote:

>Hi, sorry for the newbie questions but I do not understand how I
>can combine the resource interface with deferred callbacks.  Or,
>specifically, can anyone point me to a simple example of a .rpy
>that does a simple database call, and returns the result to the
>http response?
>
>Many thanks,
>
>Mario

I'm no expert, but you can do something like this (UNTESTED):
-----------------------------------------------------------------
# replace this import with whatever DBAPI module you use...
import cx_Oracle

# twisted imports
from twisted.internet import threads
from twisted.web import resource
from twisted.web.server import NOT_DONE_YET

def databaseOperation():
    con = cx_Oracle.connect("foo/bar at mydb.mysvr.org")
    cur = con.cursor()
    cur.execute("SELECT COUNT(*) FROM MyTable")
    databaseResult = cur.fetchall()
    cur.close()
    con.close()

    return databaseResult[0][0]

def databaseResult(result, httpRequest):
    httpRequest.write(result)
    httpRequest.finish()

class MyResource(resource.Resource):
    def render(self, request):
        d = threads.deferToThread(databaseOperation)
        d.addCallback(databaseResult, request)
        return NOT_DONE_YET

resource = MyResource()
-----------------------------------------------------------------

Of course, you could also use twisted.enterprise.adbapi, but I've experienced a lot of memory leaks occurring when going that route, so I just use deferToThread instead.

There is probably a better way to code this, but I'm not far enough along in my Python/Twisted experience to provide it.

L. Daniel Burr




More information about the Twisted-Python mailing list