Asynchronous HTTP Responses using twisted.web

In Twisted web, Resources may generate it’s response asynchronously rather than immediately upon the call to its render method. This is different from other synchronous python frameworks like django, flask etc. In those frameworks response has to be returned at the end of view function execution.

I used NOT_DONE_YET method to return response asynchronously. Also, used resource and render method to implement.

Conceptual Overview:

from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET,Site
from twisted.internet import reactor

class ShowResource(Resource):
    isLeaf =  True
    def printRequest(self,request):
        request.write('Hi, Your response are ready.')

    def render_GET(self,request):
        req = request
        return NOT_DONE_YET

root = ShowResource()
factory = Site(root)
reactor.listenTCP(8082, factory)


I used request.write() method for resource to respond instead of returning string.
This method can be called repeatedly. Each call appends another string to the response body. Once response body has been passed to request.write, the application must call request.finish . request.finish, ends the response. To generate response asynchronously, render method must return NOT_DONE_YET. If you do not call request.finish() you will get awaiting response mode. Meaning, browser still waits for full response, twisted won’t end the request until request.finish() is called.

To run this, save a file and run as a python script.
Then, open web browser and enter url “localhost:8082”.
You will see awaiting response for 10 seconds and then response arrives.

Leave a Reply

Your email address will not be published. Required fields are marked *