Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22462

Lintel Technologies: Asynchronous HTTP Responses using twisted.web

$
0
0

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:

123

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.')
        request.finish()


    def render_GET(self,request):
        req = request
        reactor.callLater(10,self.printRequest,req)
        return NOT_DONE_YET

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

 

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.

The post Asynchronous HTTP Responses using twisted.web appeared first on Lintel Technologies Blog.


Viewing all articles
Browse latest Browse all 22462

Trending Articles