[Twisted-Python] twisted.web2 server timeout?

Paul Perez paul at paulperez.net
Mon Jul 2 22:16:54 EDT 2007


 I have a newbie question. By the way, even though it is a brain-f**k, I
love programming in this software. I just wish there was an easier/faster
way to understand it. I got and read the twisted book, but unfortunately it
does not have twisted web2 examples...

Anyway, I have written a web server using web2 that takes an HTTP request
and sends it off to another server to process it. If the other server were
to crash, how can I make the http request timeout after 30 seconds and
redirect to a timeout page?

Following is my resource code. When the response is available, I take the
response stream, write to it, and call finish().

class HTTPServer(resource.PostableResource):

    def __init__(self, cache):
        resource.Resource.__init__(self)
        self.cache = cache

    def _finished(self, result, httprequest, postdata):
        convq = self.cache['conversations']
        s=stream.ProducerStream()
        self.cache['requests'][id(httprequest)] = (httprequest,postdata,s)
        if httprequest.args.has_key(CONVID):
            conversationid = httprequest.args[CONVID][0]
            try:
                convq[conversationid].put(httprequest)
            except:
                convq[conversationid] = Queue.Queue()
                convq[conversationid].put(httprequest)
        else:
            convq[ANY].put(httprequest)
        if log:
            method       = httprequest.method
            raw_uri      = urllib.unquote(httprequest.uri)
            print "%-4s" % method,
            print "%-6s" % 'CLIENT',
            print "%-4s" % raw_uri

        return http.Response(stream=s)

    def _failed(self, reason, httprequest, postdata):
        result = str(reason)
        result += str(httprequest.uri) + '\n'
        result += '\n'.join(postdata) + '\n'
        return http.Response(500, stream="An internal server error has
occurred.")

    def http_POST(self, httprequest):
        postdata = []
        d = stream.readStream(httprequest.stream, postdata.append)
        d.addCallbacks(
            self._finished,
            self._failed,
            callbackArgs=(httprequest, postdata,),
            errbackArgs=(httprequest, postdata,)
        )

        # Catch any errors that occur in self._finished.
        d.addErrback(self._failed, httprequest, postdata)

        return d

    http_PUT = http_POST
    http_GET = http_POST



~Paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://twistedmatrix.com/pipermail/twisted-python/attachments/20070702/207ba243/attachment.htm 


More information about the Twisted-Python mailing list