[Twisted-web] database best practices
Phil Mayers
p.mayers at imperial.ac.uk
Tue Nov 25 04:58:37 EST 2008
Abdul-Wahid Paterson wrote:
> Hi
>
> I thought the twisted enterprise was meant to be more suited...
>
> http://twistedmatrix.com/projects/core/documentation/howto/enterprise.html
>
> (Sorry Martin for hijacking your question but I think we want to know
> the same thing). Anyway, the method on this page sounds good but I
> wasn't actually sure how I fit this in with the renderers. Especially,
> there are some SQL queries I want to do before rendering anything on the
> page and perhaps before even sending HTTP header information. If I am
> calling the deffered from renderHTTP how do I use the result within
> renderHTTP.
>
> An example would be nice :)
That's a pretty elementary question. Perhaps someone could add a simple
example like this to the twisted.web docs?
from twisted.web import resource, server
from twisted.enterprise import adbapi
mypool = adbapi.ConnectionPool(...)
class page(resource.Resource)
def render_GET(self, request):
d = mypool.runInteraction(self.query, request_args)
d.addCallback(self.ok, request)
d.addErrback(self.err, request)
return server.NOT_DONE_YET
def query(self, cursor, request_args):
"""I run in a thread. Do database stuff here"""
cursor.execute(...)
return cursor.fetchall()
def ok(self, results, request):
request.write("""<html>...""")
for row in results:
request.write(...row...)
request.finish()
def ok(self, failure, request):
request.write("""<html><body><h2>Error</h2>""")
request.write(failure.getErrorMessage())
request.write("""</body></html>""")
request.finish()
More information about the Twisted-web
mailing list