[Twisted-Python] blocking question

Andrew Bennetts andrew-twisted at puzzling.org
Thu Apr 17 23:43:11 EDT 2003


On Thu, Apr 17, 2003 at 11:15:06PM -0400, Konrad Rokicki wrote:
> Hey everyone, newbie question:
> Are there any Python/Twisted idioms for doing blocking? More specifically,
> in a client I have a method to send a query to the server and another
> method that gets called when the query is answered. Is there an easy way
> to say "send the query then wait x seconds for it to return in this
> function"?
> It seems like blocking is taboo in twisted and if anyone has an
> alternative I'd be glad to hear it. I guess I could do this
> asynchronically but it would be a pain I think.

This is what Deferreds are for.  Your client should look something like
this:

    from twisted.internet.defer import Deferred
    from twisted.protocols.basic import LineReceiver
    
    class MyClient(LineReceiver):
        """A very simple protocol that sends one line 'queries', and
        receives one line answers in response.  An answer that startswith
        'Result:' is considered a successful response; anything else is an
        error response."""
        
        def sendQuery(queryString):
            self.sendLine(queryString)
            self.queryDeferred = Deferred()
            return queryDeferred
    
        def lineReceived(line):
            if line.startswith('Result:'):
                self.queryDeferred.callback(line[7:])
            else:
                self.queryDeferred.errback(line)
            self.queryDeferred = None


This is obviously a rather stupid protocol.
    
Then, to perform a query:

    # Assume we've already got a connected MyClient instance in the variable
    # 'myclient'.
    
    # Define a callback and an errback.
    def printResult(result, query):
        print 'Result of query %r is: %r' % (query, result)

    def printFailure(failure, query):
        print 'Query %r failed:' % query
        failure.printTraceback()

    # Send the query
    query = 'query string'
    deferred = myclient.sendQuery(query)

    # Set a timeout
    deferred.setTimeout(10)

    # Attach callback/errback to handle the result
    deferred.addCallback(printResult, query)
    deferred.addErrback(printResult, query)
    
    
See http://twistedmatrix.com/documents/howto/defer for more details on using
Deferreds.  See also the "Writing a Server" and "Writing a Client" howtos.
This is pretty basic Twisted stuff, so the existing docs cover it pretty
well.

-Andrew.





More information about the Twisted-Python mailing list