[Twisted-web] Deferred 101

Phil Mayers p.mayers at imperial.ac.uk
Tue Jul 5 03:01:04 EDT 2011

On 07/05/2011 05:14 AM, mayvimmer at fibertel.com.ar wrote:
> Hi guys,
>   I'm totally new to Twisted although everything I try so far has been a lot of
> fun. I have a really simple situation it seems I cannot wrap my head around.
> Although the tutorial have been really helpful I cannof find how to fix this
> last part.
> I created a "login" method that connects with my db through adbapi and
> returns a deferred. I'm using it with pyamf and it's working ok. Now I have to
> implement the same thing but accept logins through a standard web page. I
> followed the Twisted web in 60 seconds tutorial and created a render_POST
> method that processes the login method. The only catch is that I'm returning a
> mako template page. Ok, finally my problem: I cannot make it return the result
> of the deferred: if I debug the response I see a "<Deferred at ...>" but
> not the intended message. Actually if I add a callback method that just prints
> the response, I can get it (but since that prints the message in the log, it
> doesn't help). What am I missing?

The problem is almost certainly that Mako is not deferred-aware. If it 
were, it would stop the render when encountering a deferred and re-start 
when the deferred callback runs. But if it were, the return value of 
it's render method would almost certainly itself be a deferred, which of 
course it's not.

Try something this:

def render_POST(self, request):
   d = myDeferredMethod()
   def render(value):
     request.write(template.render(...., value=value))
   return NOT_DONE_YET

i.e. add a callback to the deferred which does the rendering for you 
only when the result is available.

FWIF the recently added twisted.web.template handles deferred natively.

More information about the Twisted-web mailing list