[Twisted-web] web2 and database handling
christian simms
christian.simms at gmail.com
Wed Dec 13 10:48:56 CST 2006
On 12/13/06, Łukasz Biedrycki <lukasz.biedrycki at gmail.com> wrote:
> On 13/12/06, Mircea Amarascu <mircea at ag-projects.com> wrote:
> > Hello,
> >
> > I want to attach the result of a database SELECT query to the response of
> > a HTTP GET request.
> >
> > In twisted.web I've done it this way:
> >
> > ------------------------------
> > from twisted.web import resource, server, http
> > from twisted.enterprise import adbapi
> >
> > class Site(resource.Resource):
> > ...
> >
> > def render(self, request):
> > query = "SELECT data FROM test"
> > self.db.runQuery(query).addCallback(
> > self._gotData, request).addErrback(
> > self._dbError, request)
> > return server.NOT_DONE_YET
>
> Hi,
> I've resolved it replacing
> return server.NOT_DONE_YET
> with
> return defer.Deferred()
>
> But I'm not sure is this a best way.
>
>
> >
> > def _gotData(self, results, request):
> > request.write("%s" % data[0])
> > request.write(body)
> > request.finish()
> >
> > def _dbError(self, failure, request):
> > request.setResponseCode(http.INTERNAL_SERVER_ERROR)
> > request.write("Error fetching data.")
> > request.finish()
> > ------------------------------
> >
> > What is the best way to perform the same operation in web2? A
> > web2.server.NOT_DONE_YET constant is not defined.
> >
> > In other words, how could I return a defer-related response
> > instead of a simple http.Response object ?
> >
> > Thank you.
> >
> > _______________________________________________
> > Twisted-web mailing list
> > Twisted-web at twistedmatrix.com
> > http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web
> >
>
>
> --
> Regards,
> Łukasz "Lou" Biedrycki
>
> "Hard work often pays off after time,
> but laziness always pays off now."
>
> _______________________________________________
> Twisted-web mailing list
> Twisted-web at twistedmatrix.com
> http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web
I think a better way is to directly return your Deferred to the render
method, like so:
------------------------------
from twisted.web import resource, server, http
from twisted.enterprise import adbapi
class Site(resource.Resource):
...
def render(self, request):
query = "SELECT data FROM test"
return self.db.runQuery(query).addCallback(
self._gotData, request).addErrback(
self._dbError, request)
def _gotData(self, results, request):
return [ "%s" % data[0] +
request.write(body)
]
def _dbError(self, failure, request):
request.setResponseCode(http.INTERNAL_SERVER_ERROR)
return "Error fetching data."
------------------------------
Cheers,
Christian
More information about the Twisted-web
mailing list