Home:ALL Converter>Twisted async request processing

Twisted async request processing

Ask Time:2011-11-16T15:22:49         Author:Stan

Json Formatter

How can I do async request processing in Twisted like in Node.js?

I wrote sample with Twisted, but my app still waited an answer from long operation(I emulate this with time.sleep).

Also I don't understand how can I use reactor.callLater correct.

This is my sample of twisted app.


from twisted.web import server
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.internet.defer import Deferred
import time

class Hello(Resource):
    def getChild(self, name, request):
        if name == '':
            return self
        print name
        return Resource.getChild(self, name, request)

    def render_GET(self, req):
        d = Deferred()
        reactor.callLater(2, d.callback, None)
        d.addCallback(lambda _: self.say_hi(req))
        return server.NOT_DONE_YET

    def say_hi(self, req):
        req.setHeader("content-type", "text/html")
        time.sleep(5)
        req.write("hello!")
        req.finish()

class Hello2(Resource):
    isLeaf = True
    def render_GET(self, req):
        req.setHeader("content-type", "text/html")
        return "hello2!"

root = Hello()
root.putChild("2", Hello2())
reactor.listenTCP(8080, server.Site(root))
reactor.run()

Edit: Now question is how to write a sync code? Please example.

Author:Stan,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/8148048/twisted-async-request-processing
yy