[Twisted-web] Using deferreds to render a page

Grant Baillie grant at osafoundation.org
Mon Dec 5 11:27:40 MST 2005


On Dec 5, 2005, at 10:16 , A. Goryunov wrote:

> I might be just dumb, but I can't figure out the correct way to do  
> what the following passage from Twisted.web's Howto suggests:
>
> "/Request a |Deferred|, return |server.NOT_DONE_YET|, and call | 
> request.write("stuff")| and |request.finish()| later, in a callback  
> on the |Deferred|/."
>
> How do I get at the request object from a callback function? All  
> the documentation on Deferreds that I managed to find uses print's  
> to display results, but that doesn't help any, since I intend to  
> present output to a remote user rather than myself. For now I've  
> settled with using the following method:
>
> class PrintResult(object):
>
>    def __init__(self, request):
>
>        self.request = request
>
>
>    def __call__(self, *args):
>
>        l = args[0]
>
>        if l:
>
>            self.request.write("<html>ID is %s</html>" % str(l[0][0]))
>
>        else:
>
>            self.request.write( "<html>No ID found</html>")
>
>        self.request.finish()
>
>        return server.NOT_DONE_YET
>
>
> So that the request is stored inside the callback itself, but this  
> somehow feels  wrong. Is there some standard way of doing this that  
> I am missing?

One way is to define the callback within the scope of request (and  
self, your Resource), and let Python do the rest for you. E.g.


def render_GET(self, request):

     def finishUp(result):
        # .... do something interesting with result ...

         request.finish()


     d = self.makeADeferred(request)
     d.addCallback(finishUp) # You also need an errback here!
     return server.NOT_DONE_YET

--Grant

Grant Baillie
Open Source Applications Foundation
http://www.osafoundation.org






More information about the Twisted-web mailing list